diff --git a/src/AppConfiguration/AppConfiguration.sln b/src/AppConfiguration/AppConfiguration.sln new file mode 100644 index 000000000000..42804172247d --- /dev/null +++ b/src/AppConfiguration/AppConfiguration.sln @@ -0,0 +1,48 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Accounts", "..\Accounts\Accounts\Accounts.csproj", "{142D7B0B-388A-4CEB-A228-7F6D423C5C2E}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authentication", "..\Accounts\Authentication\Authentication.csproj", "{62843FE6-7575-4D88-B989-7DF7EEC0BC01}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authentication.ResourceManager", "..\Accounts\Authentication.ResourceManager\Authentication.ResourceManager.csproj", "{442C609B-A431-4A71-B289-08F0B63C83E5}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authenticators", "..\Accounts\Authenticators\Authenticators.csproj", "{59E8F6B8-8F0E-403F-B88B-9736DBC396D9}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Az.AppConfiguration", "Az.AppConfiguration.csproj", "{967FAB03-A165-41CC-B3B5-02A73B88F7F9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Release|Any CPU.Build.0 = Release|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Debug|Any CPU.Build.0 = Debug|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Release|Any CPU.ActiveCfg = Release|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Release|Any CPU.Build.0 = Release|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Release|Any CPU.Build.0 = Release|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Release|Any CPU.Build.0 = Release|Any CPU + {967FAB03-A165-41CC-B3B5-02A73B88F7F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {967FAB03-A165-41CC-B3B5-02A73B88F7F9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {967FAB03-A165-41CC-B3B5-02A73B88F7F9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {967FAB03-A165-41CC-B3B5-02A73B88F7F9}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F9B3D96E-9680-40BE-A917-02EE655D6030} + EndGlobalSection +EndGlobal diff --git a/src/AppConfiguration/Az.AppConfiguration.csproj b/src/AppConfiguration/Az.AppConfiguration.csproj new file mode 100644 index 000000000000..aff60619e9be --- /dev/null +++ b/src/AppConfiguration/Az.AppConfiguration.csproj @@ -0,0 +1,7 @@ + + + AppConfiguration + + + + \ No newline at end of file diff --git a/src/AppConfiguration/Az.AppConfiguration.format.ps1xml b/src/AppConfiguration/Az.AppConfiguration.format.ps1xml new file mode 100644 index 000000000000..d133e8a07c00 --- /dev/null +++ b/src/AppConfiguration/Az.AppConfiguration.format.ps1xml @@ -0,0 +1,557 @@ + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.AppConfigurationIdentity + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.AppConfigurationIdentity + + + + + + + + + + + + + + + + + + ConfigStoreName + + + ResourceGroupName + + + SubscriptionId + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ApiKey + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ApiKey + + + + + + + + + + + + + + + + + + + + + + + + ConnectionString + + + LastModified + + + Name + + + ReadOnly + + + Value + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ApiKeyListResult + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ApiKeyListResult + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.CheckNameAvailabilityParameters + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.CheckNameAvailabilityParameters + + + + + + + + + + + + + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStore + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStore + + + + + + + + + + + + + + + + + + Location + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreListResult + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreListResult + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreProperties + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreProperties + + + + + + + + + + + + + + + + + + CreationDate + + + Endpoint + + + ProvisioningState + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreUpdateParametersTags + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreUpdateParametersTags + + + + + + + + + + + + Item + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.Error + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.Error + + + + + + + + + + + + + + + Code + + + Message + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.KeyValue + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.KeyValue + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ContentType + + + ETag + + + Key + + + Label + + + LastModified + + + Locked + + + Value + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.KeyValueTags + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.KeyValueTags + + + + + + + + + + + + Item + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ListKeyValueParameters + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ListKeyValueParameters + + + + + + + + + + + + + + + Key + + + Label + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.NameAvailabilityStatus + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.NameAvailabilityStatus + + + + + + + + + + + + + + + + + + Message + + + NameAvailable + + + Reason + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.OperationDefinition + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.OperationDefinition + + + + + + + + + + + + Name + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.OperationDefinitionDisplay + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.OperationDefinitionDisplay + + + + + + + + + + + + + + + + + + + + + Description + + + Operation + + + Provider + + + Resource + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.OperationDefinitionListResult + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.OperationDefinitionListResult + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.Resource + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.Resource + + + + + + + + + + + + + + + + + + Location + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ResourceTags + + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ResourceTags + + + + + + + + + + + + Item + + + + + + + + \ No newline at end of file diff --git a/src/AppConfiguration/Az.AppConfiguration.psd1 b/src/AppConfiguration/Az.AppConfiguration.psd1 new file mode 100644 index 000000000000..5c3c1afcb057 --- /dev/null +++ b/src/AppConfiguration/Az.AppConfiguration.psd1 @@ -0,0 +1,136 @@ +# +# Module manifest for module 'Az.AppConfiguration' +# +# Generated by: Microsoft Corporation +# +# Generated on: 5/6/2020 +# + +@{ + +# Script module or binary module file associated with this manifest. +RootModule = './Az.AppConfiguration.psm1' + +# Version number of this module. +ModuleVersion = '0.1.4' + +# Supported PSEditions +CompatiblePSEditions = 'Core', 'Desktop' + +# ID used to uniquely identify this module +GUID = '3ff16738-381e-4d5a-9d90-c7ef6816f78e' + +# Author of this module +Author = 'Microsoft Corporation' + +# Company or vendor of this module +CompanyName = 'Microsoft Corporation' + +# Copyright statement for this module +Copyright = 'Microsoft Corporation. All rights reserved.' + +# Description of the functionality provided by this module +Description = 'Microsoft Azure PowerShell: AppConfiguration cmdlets' + +# Minimum version of the PowerShell engine required by this module +PowerShellVersion = '5.1' + +# Name of the PowerShell host required by this module +# PowerShellHostName = '' + +# Minimum version of the PowerShell host required by this module +# PowerShellHostVersion = '' + +# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. +DotNetFrameworkVersion = '4.7.2' + +# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. +# CLRVersion = '' + +# Processor architecture (None, X86, Amd64) required by this module +# ProcessorArchitecture = '' + +# Modules that must be imported into the global environment prior to importing this module +RequiredModules = @(@{ModuleName = 'Az.Accounts'; ModuleVersion = '1.7.5'; }) + +# Assemblies that must be loaded prior to importing this module +RequiredAssemblies = './bin/Az.AppConfiguration.private.dll' + +# Script files (.ps1) that are run in the caller's environment prior to importing this module. +# ScriptsToProcess = @() + +# Type files (.ps1xml) to be loaded when importing this module +# TypesToProcess = @() + +# Format files (.ps1xml) to be loaded when importing this module +FormatsToProcess = './Az.AppConfiguration.format.ps1xml' + +# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess +# NestedModules = @() + +# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. +FunctionsToExport = 'Get-AzAppConfigurationStore', 'Get-AzAppConfigurationStoreKey', + 'New-AzAppConfigurationStore', 'New-AzAppConfigurationStoreKey', + 'Remove-AzAppConfigurationStore', + 'Test-AzAppConfigurationStoreNameAvailability', + 'Update-AzAppConfigurationStore' + +# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. +CmdletsToExport = @() + +# Variables to export from this module +# VariablesToExport = @() + +# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. +AliasesToExport = '*' + +# DSC resources to export from this module +# DscResourcesToExport = @() + +# List of all modules packaged with this module +# ModuleList = @() + +# List of all files packaged with this module +# FileList = @() + +# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. +PrivateData = @{ + + PSData = @{ + + # Tags applied to this module. These help with module discovery in online galleries. + Tags = 'Azure','ResourceManager','ARM','PSModule','AppConfiguration' + + # A URL to the license for this module. + LicenseUri = 'https://aka.ms/azps-license' + + # A URL to the main website for this project. + ProjectUri = 'https://github.com/Azure/azure-powershell' + + # A URL to an icon representing this module. + # IconUri = '' + + # ReleaseNotes of this module + ReleaseNotes = '' + + # Prerelease string of this module + # Prerelease = '' + + # Flag to indicate whether the module requires explicit user acceptance for install/update/save + # RequireLicenseAcceptance = $false + + # External dependent modules of this module + # ExternalModuleDependencies = @() + + } # End of PSData hashtable + + } # End of PrivateData hashtable + +# HelpInfo URI of this module +# HelpInfoURI = '' + +# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. +# DefaultCommandPrefix = '' + +} + diff --git a/src/AppConfiguration/Az.AppConfiguration.psm1 b/src/AppConfiguration/Az.AppConfiguration.psm1 new file mode 100644 index 000000000000..e49f557216e9 --- /dev/null +++ b/src/AppConfiguration/Az.AppConfiguration.psm1 @@ -0,0 +1,109 @@ +# region Generated + # ---------------------------------------------------------------------------------- + # + # 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. + # ---------------------------------------------------------------------------------- + # Load required Az.Accounts module + $accountsName = 'Az.Accounts' + $accountsModule = Get-Module -Name $accountsName + if(-not $accountsModule) { + $localAccountsPath = Join-Path $PSScriptRoot 'generated\modules' + if(Test-Path -Path $localAccountsPath) { + $localAccounts = Get-ChildItem -Path $localAccountsPath -Recurse -Include 'Az.Accounts.psd1' | Select-Object -Last 1 + if($localAccounts) { + $accountsModule = Import-Module -Name ($localAccounts.FullName) -Scope Global -PassThru + } + } + if(-not $accountsModule) { + $hasAdequateVersion = (Get-Module -Name $accountsName -ListAvailable | Where-Object { $_.Version -ge [System.Version]'1.7.4' } | Measure-Object).Count -gt 0 + if($hasAdequateVersion) { + $accountsModule = Import-Module -Name $accountsName -MinimumVersion 1.7.4 -Scope Global -PassThru + } + } + } + + if(-not $accountsModule) { + Write-Error "`nThis module requires $accountsName version 1.7.4 or greater. For installation instructions, please see: https://docs.microsoft.com/en-us/powershell/azure/install-az-ps" -ErrorAction Stop + } elseif (($accountsModule.Version -lt [System.Version]'1.7.4') -and (-not $localAccounts)) { + Write-Error "`nThis module requires $accountsName version 1.7.4 or greater. An earlier version of Az.Accounts is imported in the current PowerShell session. If you are running test, please try to remove '.PSSharedModules' in your home directory. Otherwise please open a new PowerShell session and import this module again.`nAdditionally, this error could indicate that multiple incompatible versions of Azure PowerShell modules are installed on your system. For troubleshooting information, please see: https://aka.ms/azps-version-error" -ErrorAction Stop + } + Write-Information "Loaded Module '$($accountsModule.Name)'" + + # Load the private module dll + $null = Import-Module -Name (Join-Path $PSScriptRoot './bin/Az.AppConfiguration.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module]::Instance + + # Ask for the shared functionality table + $VTable = Register-AzModule + + # Tweaks the pipeline on module load + $instance.OnModuleLoad = $VTable.OnModuleLoad + + # Tweaks the pipeline per call + $instance.OnNewRequest = $VTable.OnNewRequest + + # Gets shared parameter values + $instance.GetParameterValue = $VTable.GetParameterValue + + # Allows shared module to listen to events from this module + $instance.EventListener = $VTable.EventListener + + # Gets shared argument completers + $instance.ArgumentCompleter = $VTable.ArgumentCompleter + + # The name of the currently selected Azure profile + $instance.ProfileName = $VTable.ProfileName + + + # Load the custom module + $customModulePath = Join-Path $PSScriptRoot './custom/Az.AppConfiguration.custom.psm1' + if(Test-Path $customModulePath) { + $null = Import-Module -Name $customModulePath + } + + # Export nothing to clear implicit exports + Export-ModuleMember + + # Export proxy cmdlet scripts + $exportsPath = Join-Path $PSScriptRoot './exports' + $directories = Get-ChildItem -Directory -Path $exportsPath + $profileDirectory = $null + if($instance.ProfileName) { + if(($directories | ForEach-Object { $_.Name }) -contains $instance.ProfileName) { + $profileDirectory = $directories | Where-Object { $_.Name -eq $instance.ProfileName } + } else { + # Don't export anything if the profile doesn't exist for the module + $exportsPath = $null + Write-Warning "Selected Azure profile '$($instance.ProfileName)' does not exist for module '$($instance.Name)'. No cmdlets were loaded." + } + } elseif(($directories | Measure-Object).Count -gt 0) { + # Load the last folder if no profile is selected + $profileDirectory = $directories | Select-Object -Last 1 + } + + if($profileDirectory) { + Write-Information "Loaded Azure profile '$($profileDirectory.Name)' for module '$($instance.Name)'" + $exportsPath = $profileDirectory.FullName + } + + if($exportsPath) { + Get-ChildItem -Path $exportsPath -Recurse -Include '*.ps1' -File | ForEach-Object { . $_.FullName } + $cmdletNames = Get-ScriptCmdlet -ScriptFolder $exportsPath + Export-ModuleMember -Function $cmdletNames -Alias (Get-ScriptCmdlet -ScriptFolder $exportsPath -AsAlias) + } + + # Finalize initialization of this module + $instance.Init(); + Write-Information "Loaded Module '$($instance.Name)'" +# endregion diff --git a/src/AppConfiguration/ChangeLog.md b/src/AppConfiguration/ChangeLog.md new file mode 100644 index 000000000000..21f451768e51 --- /dev/null +++ b/src/AppConfiguration/ChangeLog.md @@ -0,0 +1,32 @@ + +## Upcoming Release + +## Version 0.1.4 + +## Version 0.1.3 + +## Version 0.1.2 + +## Version 0.1.1 + +## Version 0.1.0 +* the first preview release + diff --git a/src/AppConfiguration/MSSharedLibKey.snk b/src/AppConfiguration/MSSharedLibKey.snk new file mode 100644 index 000000000000..695f1b38774e Binary files /dev/null and b/src/AppConfiguration/MSSharedLibKey.snk differ diff --git a/src/AppConfiguration/Properties/AssemblyInfo.cs b/src/AppConfiguration/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..465ba1f3f365 --- /dev/null +++ b/src/AppConfiguration/Properties/AssemblyInfo.cs @@ -0,0 +1,28 @@ +// ---------------------------------------------------------------------------------- +// +// 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.Reflection; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("Microsoft Azure Powershell - AppConfiguration")] +[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)] +[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)] +[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)] + +[assembly: ComVisible(false)] +[assembly: CLSCompliant(false)] +[assembly: Guid("35EEFC24-4DBE-4ADD-BEEE-A1894A7301F3")] +[assembly: AssemblyVersion("0.1.4")] +[assembly: AssemblyFileVersion("0.1.4")] \ No newline at end of file diff --git a/src/AppConfiguration/build-module.ps1 b/src/AppConfiguration/build-module.ps1 new file mode 100644 index 000000000000..658ba1f7f1e2 --- /dev/null +++ b/src/AppConfiguration/build-module.ps1 @@ -0,0 +1,153 @@ +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Run, [switch]$Test, [switch]$Docs, [switch]$Pack, [switch]$Code, [switch]$Release, [switch]$Debugger, [switch]$NoDocs) +$ErrorActionPreference = 'Stop' + +if($PSEdition -ne 'Core') { + Write-Error 'This script requires PowerShell Core to execute. [Note] Generated cmdlets will work in both PowerShell Core or Windows PowerShell.' +} + +if(-not $Isolated -and -not $Debugger) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + + if($LastExitCode -ne 0) { + # Build failed. Don't attempt to run the module. + return + } + + if($Test) { + . (Join-Path $PSScriptRoot 'test-module.ps1') + if($LastExitCode -ne 0) { + # Tests failed. Don't attempt to run the module. + return + } + } + + if($Docs) { + . (Join-Path $PSScriptRoot 'generate-help.ps1') + if($LastExitCode -ne 0) { + # Docs generation failed. Don't attempt to run the module. + return + } + } + + if($Pack) { + . (Join-Path $PSScriptRoot 'pack-module.ps1') + if($LastExitCode -ne 0) { + # Packing failed. Don't attempt to run the module. + return + } + } + + $runModulePath = Join-Path $PSScriptRoot 'run-module.ps1' + if($Code) { + . $runModulePath -Code + } elseif($Run) { + . $runModulePath + } else { + Write-Host -ForegroundColor Cyan "To run this module in an isolated PowerShell session, run the 'run-module.ps1' script or provide the '-Run' parameter to this script." + } + return +} + +$binFolder = Join-Path $PSScriptRoot 'bin' +$objFolder = Join-Path $PSScriptRoot 'obj' + +if(-not $Debugger) { + Write-Host -ForegroundColor Green 'Cleaning build folders...' + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path $binFolder, $objFolder + + if((Test-Path $binFolder) -or (Test-Path $objFolder)) { + Write-Host -ForegroundColor Cyan 'Did you forget to exit your isolated module session before rebuilding?' + Write-Error 'Unable to clean ''bin'' or ''obj'' folder. A process may have an open handle.' + } + + Write-Host -ForegroundColor Green 'Compiling module...' + $buildConfig = 'Debug' + if($Release) { + $buildConfig = 'Release' + } + dotnet publish $PSScriptRoot --verbosity quiet --configuration $buildConfig /nologo + if($LastExitCode -ne 0) { + Write-Error 'Compilation failed.' + } + + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path (Join-Path $binFolder 'Debug'), (Join-Path $binFolder 'Release') +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.AppConfiguration.private.dll' +if(-not (Test-Path $dll)) { + Write-Error "Unable to find output assembly in '$binFolder'." +} + +# Load DLL to use build-time cmdlets +$null = Import-Module -Name $dll + +$modulePaths = $dll +$customPsm1 = Join-Path $PSScriptRoot 'custom\Az.AppConfiguration.custom.psm1' +if(Test-Path $customPsm1) { + $modulePaths = @($dll, $customPsm1) +} + +$exportsFolder = Join-Path $PSScriptRoot 'exports' +if(Test-Path $exportsFolder) { + $null = Get-ChildItem -Path $exportsFolder -Recurse -Exclude 'readme.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue +} +$null = New-Item -ItemType Directory -Force -Path $exportsFolder + +$internalFolder = Join-Path $PSScriptRoot 'internal' +if(Test-Path $internalFolder) { + $null = Get-ChildItem -Path $internalFolder -Recurse -Exclude '*.psm1', 'readme.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue +} +$null = New-Item -ItemType Directory -Force -Path $internalFolder + +$psd1 = Join-Path $PSScriptRoot './Az.AppConfiguration.psd1' +$guid = Get-ModuleGuid -Psd1Path $psd1 +$moduleName = 'Az.AppConfiguration' +$examplesFolder = Join-Path $PSScriptRoot 'examples' +$null = New-Item -ItemType Directory -Force -Path $examplesFolder + +if($NoDocs) { + Write-Host -ForegroundColor Green 'Creating exports...' + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ExcludeDocs +} else { + Write-Host -ForegroundColor Green 'Creating exports and docs...' + $moduleDescription = 'Microsoft Azure PowerShell: AppConfiguration cmdlets' + $docsFolder = Join-Path $PSScriptRoot 'docs' + if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'readme.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue + } + $null = New-Item -ItemType Directory -Force -Path $docsFolder + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ModuleDescription $moduleDescription -DocsFolder $docsFolder -ExamplesFolder $examplesFolder -ModuleGuid $guid +} + +Write-Host -ForegroundColor Green 'Creating format.ps1xml...' +$formatPs1xml = Join-Path $PSScriptRoot './Az.AppConfiguration.format.ps1xml' +Export-FormatPs1xml -FilePath $formatPs1xml + +Write-Host -ForegroundColor Green 'Creating psd1...' +$customFolder = Join-Path $PSScriptRoot 'custom' +Export-Psd1 -ExportsFolder $exportsFolder -CustomFolder $customFolder -Psd1Path $psd1 -ModuleGuid $guid + +Write-Host -ForegroundColor Green 'Creating test stubs...' +$testFolder = Join-Path $PSScriptRoot 'test' +$null = New-Item -ItemType Directory -Force -Path $testFolder +Export-TestStub -ModuleName $moduleName -ExportsFolder $exportsFolder -OutputFolder $testFolder + +Write-Host -ForegroundColor Green 'Creating example stubs...' +Export-ExampleStub -ExportsFolder $exportsFolder -OutputFolder $examplesFolder + +Write-Host -ForegroundColor Green '-------------Done-------------' diff --git a/src/AppConfiguration/check-dependencies.ps1 b/src/AppConfiguration/check-dependencies.ps1 new file mode 100644 index 000000000000..5cd7ab5c808f --- /dev/null +++ b/src/AppConfiguration/check-dependencies.ps1 @@ -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. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Accounts, [switch]$Pester, [switch]$Resources) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +function DownloadModule ([bool]$predicate, [string]$path, [string]$moduleName, [string]$versionMinimum) { + if($predicate) { + $module = Get-Module -ListAvailable -Name $moduleName + if((-not $module) -or ($versionMinimum -and ($module | ForEach-Object { $_.Version } | Where-Object { $_ -ge [System.Version]$versionMinimum } | Measure-Object).Count -eq 0)) { + $null = New-Item -ItemType Directory -Force -Path $path + Write-Host -ForegroundColor Green "Installing local $moduleName module into '$path'..." + if($versionMinimum) { + Find-Module -Name $moduleName -MinimumVersion $versionMinimum -Repository PSGallery | Save-Module -Path $path + } else { + Find-Module -Name $moduleName -Repository PSGallery | Save-Module -Path $path + } + } + } +} + +$ProgressPreference = 'SilentlyContinue' +$all = (@($Accounts.IsPresent, $Pester.IsPresent) | Select-Object -Unique | Measure-Object).Count -eq 1 + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +DownloadModule -predicate ($all -or $Accounts) -path $localModulesPath -moduleName 'Az.Accounts' -versionMinimum '1.7.4' +DownloadModule -predicate ($all -or $Pester) -path $localModulesPath -moduleName 'Pester' -versionMinimum '' + +$tools = Join-Path $PSScriptRoot 'tools' +$resourceDir = Join-Path $tools 'Resources' +$resourceModule = Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psm1' + +if ($Resources.IsPresent -and (-not (Test-Path -Path $resourceModule))) { + Write-Host -ForegroundColor Green "Building local Resource module used for test..." + Set-Location $resourceDir + $null = autorest-beta .\readme.md --output-folder=$HOME/.PSSharedModules/Resources + $null = Copy-Item custom/* $HOME/.PSSharedModules/Resources/custom/ + Set-Location $HOME/.PSSharedModules/Resources + $null = .\build-module.ps1 + Set-Location $PSScriptRoot +} diff --git a/src/AppConfiguration/custom/Az.AppConfiguration.custom.psm1 b/src/AppConfiguration/custom/Az.AppConfiguration.custom.psm1 new file mode 100644 index 000000000000..64a74887b5f9 --- /dev/null +++ b/src/AppConfiguration/custom/Az.AppConfiguration.custom.psm1 @@ -0,0 +1,17 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.AppConfiguration.private.dll') + + # Load the internal module + $internalModulePath = Join-Path $PSScriptRoot '..\internal\Az.AppConfiguration.internal.psm1' + if(Test-Path $internalModulePath) { + $null = Import-Module -Name $internalModulePath + } + + # Export nothing to clear implicit exports + Export-ModuleMember + + # Export script cmdlets + Get-ChildItem -Path $PSScriptRoot -Recurse -Include '*.ps1' -File | ForEach-Object { . $_.FullName } + Export-ModuleMember -Function (Get-ScriptCmdlet -ScriptFolder $PSScriptRoot) -Alias (Get-ScriptCmdlet -ScriptFolder $PSScriptRoot -AsAlias) +# endregion diff --git a/src/AppConfiguration/custom/Update-AzAppConfigurationStore.ps1 b/src/AppConfiguration/custom/Update-AzAppConfigurationStore.ps1 new file mode 100644 index 000000000000..182ca7f764b0 --- /dev/null +++ b/src/AppConfiguration/custom/Update-AzAppConfigurationStore.ps1 @@ -0,0 +1,90 @@ +<# +.Synopsis +Updates a configuration store with the specified parameters. +.Description +Updates a configuration store with the specified parameters. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/update-azappconfigurationstore +#> +function Update-AzAppConfigurationStore { +[OutputType('Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore')] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +[Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description('Updates a configuration store with the specified parameters.')] +param( + [Parameter(ParameterSetName='UpdateExpanded', Mandatory, HelpMessage='The name of the configuration store.')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + ${Name}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory, HelpMessage='The name of the resource group to which the container registry belongs.')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + ${ResourceGroupName}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory, HelpMessage='The Microsoft Azure subscription ID.')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline, HelpMessage='Identity Parameter')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + ${InputObject}, + + [Parameter(ParameterSetName='UpdateExpanded', HelpMessage='The ARM resource tags.')] + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', HelpMessage='The ARM resource tags.')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags] + ${Tag}, + + [Parameter(HelpMessage='The credentials, account, tenant, and subscription used for communication with Azure.')] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + ${DefaultProfile}, + + [Parameter(HelpMessage='Run the command as a job')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + ${AsJob}, + + [Parameter(DontShow, HelpMessage='Wait for .NET debugger to attach')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + ${Break}, + + [Parameter(DontShow, HelpMessage='SendAsync Pipeline Steps to be appended to the front of the pipeline')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + ${HttpPipelineAppend}, + + [Parameter(DontShow, HelpMessage='SendAsync Pipeline Steps to be prepended to the front of the pipeline')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + ${HttpPipelinePrepend}, + + [Parameter(DontShow, HelpMessage='The URI for the proxy server to use')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + ${Proxy}, + + [Parameter(DontShow, HelpMessage='Credentials for a proxy server to use for the remote call')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + ${ProxyCredential}, + + [Parameter(DontShow, HelpMessage='Use the default credentials for the proxy')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + ${ProxyUseDefaultCredentials} +) + +process { + Az.AppConfiguration.internal\Update-AzAppConfigurationStore @PSBoundParameters +} + +} diff --git a/src/AppConfiguration/custom/readme.md b/src/AppConfiguration/custom/readme.md new file mode 100644 index 000000000000..7e96d6bdb139 --- /dev/null +++ b/src/AppConfiguration/custom/readme.md @@ -0,0 +1,41 @@ +# Custom +This directory contains custom implementation for non-generated cmdlets for the `Az.AppConfiguration` module. Both scripts (`.ps1`) and C# files (`.cs`) can be implemented here. They will be used during the build process in `build-module.ps1`, and create cmdlets into the `..\exports` folder. The only generated file into this folder is the `Az.AppConfiguration.custom.psm1`. This file should not be modified. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: yes + +## Details +For `Az.AppConfiguration` to use custom cmdlets, it does this two different ways. We **highly recommend** creating script cmdlets, as they are easier to write and allow access to the other exported cmdlets. C# cmdlets *cannot access exported cmdlets*. + +For C# cmdlets, they are compiled with the rest of the generated low-level cmdlets into the `./bin/Az.AppConfiguration.private.dll`. The names of the cmdlets (methods) and files must follow the `[cmdletName]_[variantName]` syntax used for generated cmdlets. The `variantName` is used as the `ParameterSetName`, so use something appropriate that doesn't clash with already created variant or parameter set names. You cannot use the `ParameterSetName` property in the `Parameter` attribute on C# cmdlets. Each cmdlet must be separated into variants using the same pattern as seen in the `generated/cmdlets` folder. + +For script cmdlets, these are loaded via the `Az.AppConfiguration.custom.psm1`. Then, during the build process, this module is loaded and processed in the same manner as the C# cmdlets. The fundemental difference is the script cmdlets use the `ParameterSetName` attribute and C# cmdlets do not. To create a script cmdlet variant of a generated cmdlet, simply decorate all parameters in the script with the new `ParameterSetName` in the `Parameter` attribute. This will appropriately treat each parameter set as a separate variant when processed to be exported during the build. + +## Purpose +This allows the modules to have cmdlets that were not defined in the REST specification. It also allows combining logic using generated cmdlets. This is a level of customization beyond what can be done using the [readme configuration options](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md) that are currently available. These custom cmdlets are then referenced by the cmdlets created at build-time in the `..\exports` folder. + +## Usage +The easiest way currently to start developing custom cmdlets is to copy an existing cmdlet. For C# cmdlets, copy one from the `generated/cmdlets` folder. For script cmdlets, build the project using `build-module.ps1` and copy one of the scripts from the `..\exports` folder. After that, if you want to add new parameter sets, follow the guidelines in the `Details` section above. For implementing a new cmdlets, at minimum, please keep these parameters: +- Break +- DefaultProfile +- HttpPipelineAppend +- HttpPipelinePrepend +- Proxy +- ProxyCredential +- ProxyUseDefaultCredentials + +These provide functionality to our HTTP pipeline and other useful features. In script, you can forward these parameters using `$PSBoundParameters` to the other cmdlets you're calling within `Az.AppConfiguration`. For C#, follow the usage seen in the `ProcessRecordAsync` method. + +### Attributes +For processing the cmdlets, we've created some additional attributes: +- `Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.DescriptionAttribute` + - Used in C# cmdlets to provide a high-level description of the cmdlet. This is propegated to reference documentation via [help comments](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comment_based_help) in the exported scripts. +- `Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.DoNotExportAttribute` + - Used in C# and script cmdlets to suppress creating an exported cmdlet at build-time. These cmdlets will *not be exposed* by `Az.AppConfiguration`. +- `Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.InternalExportAttribute` + - Used in C# cmdlets to route exported cmdlets to the `..\internal`, which are *not exposed* by `Az.AppConfiguration`. For more information, see [readme.md](..\internal/readme.md) in the `..\internal` folder. +- `Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.ProfileAttribute` + - Used in C# and script cmdlets to define which Azure profiles the cmdlet supports. This is only supported for Azure (`--azure`) modules. \ No newline at end of file diff --git a/src/AppConfiguration/examples/Get-AzAppConfigurationStore.md b/src/AppConfiguration/examples/Get-AzAppConfigurationStore.md new file mode 100644 index 000000000000..093355d11d50 --- /dev/null +++ b/src/AppConfiguration/examples/Get-AzAppConfigurationStore.md @@ -0,0 +1,18 @@ +### Example 1: {{ Add title here }} +```powershell +PS C:\> {{ Add code here }} + +{{ Add output here }} +``` + +{{ Add description here }} + +### Example 2: {{ Add title here }} +```powershell +PS C:\> {{ Add code here }} + +{{ Add output here }} +``` + +{{ Add description here }} + diff --git a/src/AppConfiguration/examples/Get-AzAppConfigurationStoreKey.md b/src/AppConfiguration/examples/Get-AzAppConfigurationStoreKey.md new file mode 100644 index 000000000000..093355d11d50 --- /dev/null +++ b/src/AppConfiguration/examples/Get-AzAppConfigurationStoreKey.md @@ -0,0 +1,18 @@ +### Example 1: {{ Add title here }} +```powershell +PS C:\> {{ Add code here }} + +{{ Add output here }} +``` + +{{ Add description here }} + +### Example 2: {{ Add title here }} +```powershell +PS C:\> {{ Add code here }} + +{{ Add output here }} +``` + +{{ Add description here }} + diff --git a/src/AppConfiguration/examples/New-AzAppConfigurationStore.md b/src/AppConfiguration/examples/New-AzAppConfigurationStore.md new file mode 100644 index 000000000000..093355d11d50 --- /dev/null +++ b/src/AppConfiguration/examples/New-AzAppConfigurationStore.md @@ -0,0 +1,18 @@ +### Example 1: {{ Add title here }} +```powershell +PS C:\> {{ Add code here }} + +{{ Add output here }} +``` + +{{ Add description here }} + +### Example 2: {{ Add title here }} +```powershell +PS C:\> {{ Add code here }} + +{{ Add output here }} +``` + +{{ Add description here }} + diff --git a/src/AppConfiguration/examples/New-AzAppConfigurationStoreKey.md b/src/AppConfiguration/examples/New-AzAppConfigurationStoreKey.md new file mode 100644 index 000000000000..093355d11d50 --- /dev/null +++ b/src/AppConfiguration/examples/New-AzAppConfigurationStoreKey.md @@ -0,0 +1,18 @@ +### Example 1: {{ Add title here }} +```powershell +PS C:\> {{ Add code here }} + +{{ Add output here }} +``` + +{{ Add description here }} + +### Example 2: {{ Add title here }} +```powershell +PS C:\> {{ Add code here }} + +{{ Add output here }} +``` + +{{ Add description here }} + diff --git a/src/AppConfiguration/examples/Remove-AzAppConfigurationStore.md b/src/AppConfiguration/examples/Remove-AzAppConfigurationStore.md new file mode 100644 index 000000000000..093355d11d50 --- /dev/null +++ b/src/AppConfiguration/examples/Remove-AzAppConfigurationStore.md @@ -0,0 +1,18 @@ +### Example 1: {{ Add title here }} +```powershell +PS C:\> {{ Add code here }} + +{{ Add output here }} +``` + +{{ Add description here }} + +### Example 2: {{ Add title here }} +```powershell +PS C:\> {{ Add code here }} + +{{ Add output here }} +``` + +{{ Add description here }} + diff --git a/src/AppConfiguration/examples/Test-AzAppConfigurationStoreNameAvailability.md b/src/AppConfiguration/examples/Test-AzAppConfigurationStoreNameAvailability.md new file mode 100644 index 000000000000..093355d11d50 --- /dev/null +++ b/src/AppConfiguration/examples/Test-AzAppConfigurationStoreNameAvailability.md @@ -0,0 +1,18 @@ +### Example 1: {{ Add title here }} +```powershell +PS C:\> {{ Add code here }} + +{{ Add output here }} +``` + +{{ Add description here }} + +### Example 2: {{ Add title here }} +```powershell +PS C:\> {{ Add code here }} + +{{ Add output here }} +``` + +{{ Add description here }} + diff --git a/src/AppConfiguration/examples/Update-AzAppConfigurationStore.md b/src/AppConfiguration/examples/Update-AzAppConfigurationStore.md new file mode 100644 index 000000000000..093355d11d50 --- /dev/null +++ b/src/AppConfiguration/examples/Update-AzAppConfigurationStore.md @@ -0,0 +1,18 @@ +### Example 1: {{ Add title here }} +```powershell +PS C:\> {{ Add code here }} + +{{ Add output here }} +``` + +{{ Add description here }} + +### Example 2: {{ Add title here }} +```powershell +PS C:\> {{ Add code here }} + +{{ Add output here }} +``` + +{{ Add description here }} + diff --git a/src/AppConfiguration/export-surface.ps1 b/src/AppConfiguration/export-surface.ps1 new file mode 100644 index 000000000000..4d45d576449a --- /dev/null +++ b/src/AppConfiguration/export-surface.ps1 @@ -0,0 +1,40 @@ +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$IncludeGeneralParameters, [switch]$UseExpandedFormat) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.AppConfiguration.private.dll' +if(-not (Test-Path $dll)) { + Write-Error "Unable to find output assembly in '$binFolder'." +} +$null = Import-Module -Name $dll + +$moduleName = 'Az.AppConfiguration' +$exportsFolder = Join-Path $PSScriptRoot 'exports' +$resourcesFolder = Join-Path $PSScriptRoot 'resources' + +Export-CmdletSurface -ModuleName $moduleName -CmdletFolder $exportsFolder -OutputFolder $resourcesFolder -IncludeGeneralParameters $IncludeGeneralParameters.IsPresent -UseExpandedFormat $UseExpandedFormat.IsPresent +Write-Host -ForegroundColor Green "CmdletSurface file(s) created in '$resourcesFolder'" + +Export-ModelSurface -OutputFolder $resourcesFolder -UseExpandedFormat $UseExpandedFormat.IsPresent +Write-Host -ForegroundColor Green "ModelSurface file created in '$resourcesFolder'" + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/AppConfiguration/exports/Get-AzAppConfigurationStore.ps1 b/src/AppConfiguration/exports/Get-AzAppConfigurationStore.ps1 new file mode 100644 index 000000000000..7ba5ff08e824 --- /dev/null +++ b/src/AppConfiguration/exports/Get-AzAppConfigurationStore.ps1 @@ -0,0 +1,175 @@ + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Gets the properties of the specified configuration store. +.Description +Gets the properties of the specified configuration store. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/get-azappconfigurationstore +#> +function Get-AzAppConfigurationStore { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List1', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Get')] + [Parameter(ParameterSetName='List')] + [Parameter(ParameterSetName='List1')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter(ParameterSetName='List')] + [Parameter(ParameterSetName='List1')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Query')] + [System.String] + # A skip token is used to continue retrieving items after an operation returns a partial result. + # If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. + ${SkipToken}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.AppConfiguration.private\Get-AzAppConfigurationStore_Get'; + GetViaIdentity = 'Az.AppConfiguration.private\Get-AzAppConfigurationStore_GetViaIdentity'; + List = 'Az.AppConfiguration.private\Get-AzAppConfigurationStore_List'; + List1 = 'Az.AppConfiguration.private\Get-AzAppConfigurationStore_List1'; + } + if (('Get', 'List', 'List1') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/AppConfiguration/exports/Get-AzAppConfigurationStoreKey.ps1 b/src/AppConfiguration/exports/Get-AzAppConfigurationStoreKey.ps1 new file mode 100644 index 000000000000..356a5503b1c3 --- /dev/null +++ b/src/AppConfiguration/exports/Get-AzAppConfigurationStoreKey.ps1 @@ -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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Lists the access key for the specified configuration store. +.Description +Lists the access key for the specified configuration store. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/get-azappconfigurationstorekey +#> +function Get-AzAppConfigurationStoreKey { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Query')] + [System.String] + # A skip token is used to continue retrieving items after an operation returns a partial result. + # If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. + ${SkipToken}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + List = 'Az.AppConfiguration.private\Get-AzAppConfigurationStoreKey_List'; + } + if (('List') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/AppConfiguration/exports/New-AzAppConfigurationStore.ps1 b/src/AppConfiguration/exports/New-AzAppConfigurationStore.ps1 new file mode 100644 index 000000000000..1ae26571f60b --- /dev/null +++ b/src/AppConfiguration/exports/New-AzAppConfigurationStore.ps1 @@ -0,0 +1,188 @@ + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates a configuration store with the specified parameters. +.Description +Creates a configuration store with the specified parameters. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/new-azappconfigurationstore +#> +function New-AzAppConfigurationStore { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='CreateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(ParameterSetName='CreateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='CreateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='CreateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [System.String] + # The location of the resource. + # This cannot be changed after the resource is created. + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags]))] + [System.Collections.Hashtable] + # The tags of the resource. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.AppConfiguration.private\New-AzAppConfigurationStore_CreateExpanded'; + CreateViaIdentityExpanded = 'Az.AppConfiguration.private\New-AzAppConfigurationStore_CreateViaIdentityExpanded'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/AppConfiguration/exports/New-AzAppConfigurationStoreKey.ps1 b/src/AppConfiguration/exports/New-AzAppConfigurationStoreKey.ps1 new file mode 100644 index 000000000000..4abb9521bd13 --- /dev/null +++ b/src/AppConfiguration/exports/New-AzAppConfigurationStoreKey.ps1 @@ -0,0 +1,168 @@ + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Regenerates an access key for the specified configuration store. +.Description +Regenerates an access key for the specified configuration store. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/new-azappconfigurationstorekey +#> +function New-AzAppConfigurationStoreKey { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey])] +[CmdletBinding(DefaultParameterSetName='RegenerateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='RegenerateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(ParameterSetName='RegenerateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='RegenerateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='RegenerateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [System.String] + # The id of the key to regenerate. + ${Id}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + RegenerateExpanded = 'Az.AppConfiguration.private\New-AzAppConfigurationStoreKey_RegenerateExpanded'; + RegenerateViaIdentityExpanded = 'Az.AppConfiguration.private\New-AzAppConfigurationStoreKey_RegenerateViaIdentityExpanded'; + } + if (('RegenerateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/AppConfiguration/exports/ProxyCmdletDefinitions.ps1 b/src/AppConfiguration/exports/ProxyCmdletDefinitions.ps1 new file mode 100644 index 000000000000..63214d711a31 --- /dev/null +++ b/src/AppConfiguration/exports/ProxyCmdletDefinitions.ps1 @@ -0,0 +1,1191 @@ + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Lists the access key for the specified configuration store. +.Description +Lists the access key for the specified configuration store. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/get-azappconfigurationstorekey +#> +function Get-AzAppConfigurationStoreKey { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Query')] + [System.String] + # A skip token is used to continue retrieving items after an operation returns a partial result. + # If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. + ${SkipToken}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + List = 'Az.AppConfiguration.private\Get-AzAppConfigurationStoreKey_List'; + } + if (('List') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Gets the properties of the specified configuration store. +.Description +Gets the properties of the specified configuration store. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/get-azappconfigurationstore +#> +function Get-AzAppConfigurationStore { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List1', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Get')] + [Parameter(ParameterSetName='List')] + [Parameter(ParameterSetName='List1')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter(ParameterSetName='List')] + [Parameter(ParameterSetName='List1')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Query')] + [System.String] + # A skip token is used to continue retrieving items after an operation returns a partial result. + # If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. + ${SkipToken}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.AppConfiguration.private\Get-AzAppConfigurationStore_Get'; + GetViaIdentity = 'Az.AppConfiguration.private\Get-AzAppConfigurationStore_GetViaIdentity'; + List = 'Az.AppConfiguration.private\Get-AzAppConfigurationStore_List'; + List1 = 'Az.AppConfiguration.private\Get-AzAppConfigurationStore_List1'; + } + if (('Get', 'List', 'List1') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Regenerates an access key for the specified configuration store. +.Description +Regenerates an access key for the specified configuration store. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/new-azappconfigurationstorekey +#> +function New-AzAppConfigurationStoreKey { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey])] +[CmdletBinding(DefaultParameterSetName='RegenerateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='RegenerateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(ParameterSetName='RegenerateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='RegenerateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='RegenerateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [System.String] + # The id of the key to regenerate. + ${Id}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + RegenerateExpanded = 'Az.AppConfiguration.private\New-AzAppConfigurationStoreKey_RegenerateExpanded'; + RegenerateViaIdentityExpanded = 'Az.AppConfiguration.private\New-AzAppConfigurationStoreKey_RegenerateViaIdentityExpanded'; + } + if (('RegenerateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates a configuration store with the specified parameters. +.Description +Creates a configuration store with the specified parameters. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/new-azappconfigurationstore +#> +function New-AzAppConfigurationStore { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='CreateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(ParameterSetName='CreateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='CreateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='CreateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [System.String] + # The location of the resource. + # This cannot be changed after the resource is created. + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags]))] + [System.Collections.Hashtable] + # The tags of the resource. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.AppConfiguration.private\New-AzAppConfigurationStore_CreateExpanded'; + CreateViaIdentityExpanded = 'Az.AppConfiguration.private\New-AzAppConfigurationStore_CreateViaIdentityExpanded'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Deletes a configuration store. +.Description +Deletes a configuration store. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/remove-azappconfigurationstore +#> +function Remove-AzAppConfigurationStore { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.AppConfiguration.private\Remove-AzAppConfigurationStore_Delete'; + DeleteViaIdentity = 'Az.AppConfiguration.private\Remove-AzAppConfigurationStore_DeleteViaIdentity'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Checks whether the configuration store name is available for use. +.Description +Checks whether the configuration store name is available for use. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/test-azappconfigurationstorenameavailability +#> +function Test-AzAppConfigurationStoreNameAvailability { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus])] +[CmdletBinding(DefaultParameterSetName='CheckExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='CheckExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='CheckViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [System.String] + # The name to check for availability. + ${Name}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CheckExpanded = 'Az.AppConfiguration.private\Test-AzAppConfigurationStoreNameAvailability_CheckExpanded'; + CheckViaIdentityExpanded = 'Az.AppConfiguration.private\Test-AzAppConfigurationStoreNameAvailability_CheckViaIdentityExpanded'; + } + if (('CheckExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Updates a configuration store with the specified parameters. +.Description +Updates a configuration store with the specified parameters. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. + +TAG : The ARM resource tags. + [(Any) ]: This indicates any property can be added to this object. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/update-azappconfigurationstore +#> +function Update-AzAppConfigurationStore { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags] + # The ARM resource tags. + # To construct, see NOTES section for TAG properties and create a hash table. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.AppConfiguration.custom\Update-AzAppConfigurationStore'; + UpdateViaIdentityExpanded = 'Az.AppConfiguration.custom\Update-AzAppConfigurationStore'; + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/AppConfiguration/exports/Remove-AzAppConfigurationStore.ps1 b/src/AppConfiguration/exports/Remove-AzAppConfigurationStore.ps1 new file mode 100644 index 000000000000..fc85a1ca3fd6 --- /dev/null +++ b/src/AppConfiguration/exports/Remove-AzAppConfigurationStore.ps1 @@ -0,0 +1,180 @@ + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Deletes a configuration store. +.Description +Deletes a configuration store. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/remove-azappconfigurationstore +#> +function Remove-AzAppConfigurationStore { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.AppConfiguration.private\Remove-AzAppConfigurationStore_Delete'; + DeleteViaIdentity = 'Az.AppConfiguration.private\Remove-AzAppConfigurationStore_DeleteViaIdentity'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/AppConfiguration/exports/Test-AzAppConfigurationStoreNameAvailability.ps1 b/src/AppConfiguration/exports/Test-AzAppConfigurationStoreNameAvailability.ps1 new file mode 100644 index 000000000000..dbbc701516de --- /dev/null +++ b/src/AppConfiguration/exports/Test-AzAppConfigurationStoreNameAvailability.ps1 @@ -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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Checks whether the configuration store name is available for use. +.Description +Checks whether the configuration store name is available for use. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/test-azappconfigurationstorenameavailability +#> +function Test-AzAppConfigurationStoreNameAvailability { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus])] +[CmdletBinding(DefaultParameterSetName='CheckExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='CheckExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='CheckViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [System.String] + # The name to check for availability. + ${Name}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CheckExpanded = 'Az.AppConfiguration.private\Test-AzAppConfigurationStoreNameAvailability_CheckExpanded'; + CheckViaIdentityExpanded = 'Az.AppConfiguration.private\Test-AzAppConfigurationStoreNameAvailability_CheckViaIdentityExpanded'; + } + if (('CheckExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/AppConfiguration/exports/Update-AzAppConfigurationStore.ps1 b/src/AppConfiguration/exports/Update-AzAppConfigurationStore.ps1 new file mode 100644 index 000000000000..5cf2ed08b646 --- /dev/null +++ b/src/AppConfiguration/exports/Update-AzAppConfigurationStore.ps1 @@ -0,0 +1,174 @@ + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Updates a configuration store with the specified parameters. +.Description +Updates a configuration store with the specified parameters. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. + +TAG : The ARM resource tags. + [(Any) ]: This indicates any property can be added to this object. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/update-azappconfigurationstore +#> +function Update-AzAppConfigurationStore { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags] + # The ARM resource tags. + # To construct, see NOTES section for TAG properties and create a hash table. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.AppConfiguration.custom\Update-AzAppConfigurationStore'; + UpdateViaIdentityExpanded = 'Az.AppConfiguration.custom\Update-AzAppConfigurationStore'; + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/AppConfiguration/exports/readme.md b/src/AppConfiguration/exports/readme.md new file mode 100644 index 000000000000..a2e626da4382 --- /dev/null +++ b/src/AppConfiguration/exports/readme.md @@ -0,0 +1,20 @@ +# Exports +This directory contains the cmdlets *exported by* `Az.AppConfiguration`. No other cmdlets in this repository are directly exported. What that means is the `Az.AppConfiguration` module will run [Export-ModuleMember](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/export-modulemember) on the cmldets in this directory. The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The cmdlets generated here are created every time you run `build-module.ps1`. These cmdlets are a merge of all (excluding `InternalExport`) cmdlets from the private binary (`..\bin\Az.AppConfiguration.private.dll`) and from the `..\custom\Az.AppConfiguration.custom.psm1` module. Cmdlets that are *not merged* from those directories are decorated with the `InternalExport` attribute. This happens when you set the cmdlet to **hide** from configuration. For more information on hiding, see [cmdlet hiding](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md#cmdlet-hiding-exportation-suppression) or the [readme.md](..\internal/readme.md) in the `..\internal` folder. + +## Purpose +We generate script cmdlets out of the binary cmdlets and custom cmdlets. The format of script cmdlets are simplistic; thus, easier to generate at build time. Generating the cmdlets is required as to allow merging of generated binary, hand-written binary, and hand-written custom cmdlets. For Azure cmdlets, having script cmdlets simplifies the mechanism for exporting Azure profiles. + +## Structure +The cmdlets generated here will flat in the directory (no sub-folders) as long as there are no Azure profiles specified for any cmdlets. Azure profiles (the `Profiles` attribute) is only applied when generating with the `--azure` attribute (or `azure: true` in the configuration). When Azure profiles are applied, the folder structure has a folder per profile. Each profile folder has only those cmdlets that apply to that profile. + +## Usage +When `./Az.AppConfiguration.psm1` is loaded, it dynamically exports cmdlets here based on the folder structure and on the selected profile. If there are no sub-folders, it exports all cmdlets at the root of this folder. If there are sub-folders, it checks to see the selected profile. If no profile is selected, it exports the cmdlets in the last sub-folder (alphabetically). If a profile is selected, it exports the cmdlets in the sub-folder that matches the profile name. If there is no sub-folder that matches the profile name, it exports no cmdlets and writes a warning message. \ No newline at end of file diff --git a/src/AppConfiguration/generate-help.ps1 b/src/AppConfiguration/generate-help.ps1 new file mode 100644 index 000000000000..5cdd898c6960 --- /dev/null +++ b/src/AppConfiguration/generate-help.ps1 @@ -0,0 +1,73 @@ +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$exportsFolder = Join-Path $PSScriptRoot 'exports' +if(-not (Test-Path $exportsFolder)) { + Write-Error "Exports folder '$exportsFolder' was not found." +} + +$directories = Get-ChildItem -Directory -Path $exportsFolder +$hasProfiles = ($directories | Measure-Object).Count -gt 0 +if(-not $hasProfiles) { + $directories = Get-Item -Path $exportsFolder +} + +$docsFolder = Join-Path $PSScriptRoot 'docs' +if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'readme.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue +} +$null = New-Item -ItemType Directory -Force -Path $docsFolder -ErrorAction SilentlyContinue +$examplesFolder = Join-Path $PSScriptRoot 'examples' + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.AppConfiguration.psd1') +$modulePath = $modulePsd1.FullName +$moduleName = $modulePsd1.BaseName + +# Load DLL to use build-time cmdlets +Import-Module -Name $modulePath +Import-Module -Name (Join-Path $PSScriptRoot './bin/Az.AppConfiguration.private.dll') +$instance = [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module]::Instance +# Module info is shared per profile +$moduleInfo = Get-Module -Name $moduleName + +foreach($directory in $directories) +{ + if($hasProfiles) { + Select-AzProfile -Name $directory.Name + } + # Reload module per profile + Import-Module -Name $modulePath -Force + + $cmdletNames = Get-ScriptCmdlet -ScriptFolder $directory.FullName + $cmdletHelpInfo = $cmdletNames | ForEach-Object { Get-Help -Name $_ -Full } + $cmdletFunctionInfo = Get-ScriptCmdlet -ScriptFolder $directory.FullName -AsFunctionInfo + + $docsPath = Join-Path $docsFolder $directory.Name + $null = New-Item -ItemType Directory -Force -Path $docsPath -ErrorAction SilentlyContinue + $examplesPath = Join-Path $examplesFolder $directory.Name + + Export-HelpMarkdown -ModuleInfo $moduleInfo -FunctionInfo $cmdletFunctionInfo -HelpInfo $cmdletHelpInfo -DocsFolder $docsPath -ExamplesFolder $examplesPath + Write-Host -ForegroundColor Green "Created documentation in '$docsPath'" +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/AppConfiguration/generate-info.json b/src/AppConfiguration/generate-info.json new file mode 100644 index 000000000000..3b670898f422 --- /dev/null +++ b/src/AppConfiguration/generate-info.json @@ -0,0 +1,8 @@ +{ + "autorest_powershell": "2.1.380", + "autorest_core": "3.0.6282", + "autorest": "3.0.6149", + "swagger_commit": "2911cba6010cda91a971f6a00fd5648e00c2901f", + "node": "v10.16.0", + "autorest_remodeler": "2.1.27" +} diff --git a/src/AppConfiguration/generated/Module.cs b/src/AppConfiguration/generated/Module.cs new file mode 100644 index 000000000000..0ce434109bc9 --- /dev/null +++ b/src/AppConfiguration/generated/Module.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + using SendAsyncStepDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + using PipelineChangeDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>; + using GetParameterDelegate = global::System.Func; + using ModuleLoadPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using NewRequestPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using ArgumentCompleterDelegate = global::System.Func; + using SignalDelegate = global::System.Func, global::System.Threading.Tasks.Task>; + using EventListenerDelegate = global::System.Func, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Management.Automation.InvocationInfo, string, string, string, global::System.Exception, global::System.Threading.Tasks.Task>; + using NextDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + + /// A class that contains the module-common code and data. + public partial class Module + { + /// The currently selected profile. + public string Profile = global::System.String.Empty; + + public global::System.Net.Http.HttpClientHandler _handler = new global::System.Net.Http.HttpClientHandler(); + + /// the ISendAsync pipeline instance + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline _pipeline; + + /// the ISendAsync pipeline instance (when proxy is enabled) + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline _pipelineWithProxy; + + public global::System.Net.WebProxy _webProxy = new global::System.Net.WebProxy(); + + /// Gets completion data for azure specific fields + public ArgumentCompleterDelegate ArgumentCompleter { get; set; } + + /// The instance of the Client API + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient ClientAPI { get; set; } + + /// A delegate that gets called for each signalled event + public EventListenerDelegate EventListener { get; set; } + + /// The delegate to call to get parameter data from a common module. + public GetParameterDelegate GetParameterValue { get; set; } + + /// Backing field for property. + private static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module _instance; + + /// the singleton of this module class + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module Instance => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module._instance?? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module._instance = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module()); + + /// The Name of this module + public string Name => @"Az.AppConfiguration"; + + /// The delegate to call when this module is loaded (supporting a commmon module). + public ModuleLoadPipelineDelegate OnModuleLoad { get; set; } + + /// The delegate to call before each new request (supporting a commmon module). + public NewRequestPipelineDelegate OnNewRequest { get; set; } + + /// The name of the currently selected Azure profile + public global::System.String ProfileName { get; set; } + + /// The ResourceID for this module (azure arm). + public string ResourceId => @"Az.AppConfiguration"; + + /// The from the cmdlet + /// The HttpPipeline for the request + + partial void AfterCreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline pipeline); + + /// The from the cmdlet + /// The HttpPipeline for the request + + partial void BeforeCreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline pipeline); + + partial void CustomInit(); + + /// Creates an instance of the HttpPipeline for each call. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the cmdlet's parameterset name. + /// An instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline for the remote call. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline CreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string processRecordId, string parameterSetName = null) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline pipeline = null; + BeforeCreatePipeline(invocationInfo, ref pipeline); + pipeline = (pipeline ?? (_handler.UseProxy ? _pipelineWithProxy : _pipeline)).Clone(); + AfterCreatePipeline(invocationInfo, ref pipeline); + pipeline.Append(new Runtime.CmdInfoHandler(processRecordId, invocationInfo, parameterSetName).SendAsync); + OnNewRequest?.Invoke( invocationInfo, correlationId,processRecordId, (step)=> { pipeline.Prepend(step); } , (step)=> { pipeline.Append(step); } ); + return pipeline; + } + + /// Gets parameters from a common module. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// The name of the parameter to get the value for. + /// + /// The parameter value from the common module. (Note: this should be type converted on the way back) + /// + public object GetParameter(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string parameterName) => GetParameterValue?.Invoke( ResourceId, Name, invocationInfo, correlationId,parameterName ); + + /// Initialization steps performed after the module is loaded. + public void Init() + { + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipeline.Prepend(step); } , (step)=> { _pipeline.Append(step); } ); + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipelineWithProxy.Prepend(step); } , (step)=> { _pipelineWithProxy.Append(step); } ); + CustomInit(); + } + + /// Creates the module instance. + private Module() + { + /// constructor + ClientAPI = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient(); + _handler.Proxy = _webProxy; + _pipeline = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient())); + _pipelineWithProxy = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient(_handler))); + } + + /// The HTTP Proxy to use. + /// The HTTP Proxy Credentials + /// True if the proxy should use default credentials + public void SetProxyConfiguration(global::System.Uri proxy, global::System.Management.Automation.PSCredential proxyCredential, bool proxyUseDefaultCredentials) + { + // set the proxy configuration + _webProxy.Address = proxy; + _webProxy.BypassProxyOnLocal = false; + _webProxy.Credentials = proxyCredential ?.GetNetworkCredential(); + _webProxy.UseDefaultCredentials = proxyUseDefaultCredentials; + _handler.UseProxy = proxy != null; + } + + /// Called to dispatch events to the common module listener + /// The ID of the event + /// The cancellation token for the event + /// A delegate to get the detailed event data + /// The callback for the event dispatcher + /// The from the cmdlet + /// the cmdlet's parameterset name. + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the exception that is being thrown (if available) + /// + /// A that will be complete when handling of the event is completed. + /// + public async global::System.Threading.Tasks.Task Signal(string id, global::System.Threading.CancellationToken token, global::System.Func getEventData, SignalDelegate signal, global::System.Management.Automation.InvocationInfo invocationInfo, string parameterSetName, string correlationId, string processRecordId, global::System.Exception exception) + { + using( NoSynchronizationContext ) + { + await EventListener?.Invoke(id,token,getEventData, signal, invocationInfo, parameterSetName, correlationId,processRecordId,exception); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/AppConfigurationManagementClient.cs b/src/AppConfiguration/generated/api/AppConfigurationManagementClient.cs new file mode 100644 index 000000000000..64f9f0648e44 --- /dev/null +++ b/src/AppConfiguration/generated/api/AppConfigurationManagementClient.cs @@ -0,0 +1,2192 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// + /// Low-level API implementation for the AppConfigurationManagementClient service. + /// + public partial class AppConfigurationManagementClient + { + + /// Creates a configuration store with the specified parameters. + /// The Microsoft Azure subscription ID. + /// The name of the resource group to which the container registry belongs. + /// The name of the configuration store. + /// The parameters for creating a configuration store. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresCreate(string subscriptionId, string resourceGroupName, string configStoreName, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.AppConfiguration/configurationStores/" + + global::System.Uri.EscapeDataString(configStoreName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresCreate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Creates a configuration store with the specified parameters. + /// + /// The parameters for creating a configuration store. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.AppConfiguration/configurationStores/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var configStoreName = _match.Groups["configStoreName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.AppConfiguration/configurationStores/" + + configStoreName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresCreate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresCreate_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + // declared final-state-via: default + var asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = _response.GetFirstHeader(@"Location"); + while (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + + // get the delay before polling. (default to 30 seconds if not present) + int delay = (int)(_response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.DelayBeforePolling, $"Delaying {delay} seconds before polling.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // start the delay timer (we'll await later...) + var waiting = global::System.Threading.Tasks.Task.Delay(delay * 1000, eventListener.Token ); + + // while we wait, let's grab the headers and get ready to poll. + if (!System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Azure-AsyncOperation"))) { + asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Location"))) { + location = _response.GetFirstHeader(@"Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? _originalUri : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get); + + // and let's look at the current response body and see if we have some information we can give back to the listener + var content = await _response.Content.ReadAsStringAsync(); + await waiting; + + // check for cancellation + if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Polling, $"Polling {_uri}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + try { + if( Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + var state = json.Property("properties")?.PropertyT("provisioningState") ?? json.PropertyT("status"); + if( state is null ) + { + // the body doesn't contain any information that has the state of the LRO + // we're going to just get out, and let the consumer have the result + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Polling, $"Polled {_uri} provisioning state {state}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + switch( state?.ToString()?.ToLower() ) + { + case "succeeded": + case "failed": + case "canceled": + // we're done polling. + break; + + default: + // need to keep polling! + _response.StatusCode = global::System.Net.HttpStatusCode.Created; + continue; + } + } + } catch { + // if we run into a problem peeking into the result, + // we really don't want to do anything special. + } + } + + // check for terminal status code + if (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + continue; + } + // we are done polling, do a request on final target? + if (!string.IsNullOrWhiteSpace(_originalUri)) + { + // create a new request with the final uri + request = request.CloneAndDispose(new global::System.Uri(_originalUri), Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + break; + } + } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStore.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.Error.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// + /// Validation method for method. Call this like the actual call, but you will get + /// validation events back. + /// + /// The Microsoft Azure subscription ID. + /// The name of the resource group to which the container registry belongs. + /// The name of the configuration store. + /// The parameters for creating a configuration store. + /// an instance that will receive events. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresCreate_Validate(string subscriptionId, string resourceGroupName, string configStoreName, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore body, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(configStoreName),configStoreName); + await eventListener.AssertMinimumLength(nameof(configStoreName),configStoreName,5); + await eventListener.AssertMaximumLength(nameof(configStoreName),configStoreName,50); + await eventListener.AssertRegEx(nameof(configStoreName),configStoreName,@"^[a-zA-Z0-9_-]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Deletes a configuration store. + /// The Microsoft Azure subscription ID. + /// The name of the resource group to which the container registry belongs. + /// The name of the configuration store. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresDelete(string subscriptionId, string resourceGroupName, string configStoreName, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.AppConfiguration/configurationStores/" + + global::System.Uri.EscapeDataString(configStoreName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Deletes a configuration store. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.AppConfiguration/configurationStores/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var configStoreName = _match.Groups["configStoreName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.AppConfiguration/configurationStores/" + + configStoreName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + // declared final-state-via: default + var _finalUri = _response.GetFirstHeader(@"Location"); + var asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = _response.GetFirstHeader(@"Location"); + while (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + + // get the delay before polling. (default to 30 seconds if not present) + int delay = (int)(_response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.DelayBeforePolling, $"Delaying {delay} seconds before polling.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // start the delay timer (we'll await later...) + var waiting = global::System.Threading.Tasks.Task.Delay(delay * 1000, eventListener.Token ); + + // while we wait, let's grab the headers and get ready to poll. + if (!System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Azure-AsyncOperation"))) { + asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Location"))) { + location = _response.GetFirstHeader(@"Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? _originalUri : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get); + + // and let's look at the current response body and see if we have some information we can give back to the listener + var content = await _response.Content.ReadAsStringAsync(); + await waiting; + + // check for cancellation + if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Polling, $"Polling {_uri}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + try { + if( Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + var state = json.Property("properties")?.PropertyT("provisioningState") ?? json.PropertyT("status"); + if( state is null ) + { + // the body doesn't contain any information that has the state of the LRO + // we're going to just get out, and let the consumer have the result + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Polling, $"Polled {_uri} provisioning state {state}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + switch( state?.ToString()?.ToLower() ) + { + case "succeeded": + case "failed": + case "canceled": + // we're done polling. + break; + + default: + // need to keep polling! + _response.StatusCode = global::System.Net.HttpStatusCode.Created; + continue; + } + } + } catch { + // if we run into a problem peeking into the result, + // we really don't want to do anything special. + } + } + + // check for terminal status code + if (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + continue; + } + // we are done polling, do a request on final target? + if (!string.IsNullOrWhiteSpace(_finalUri)) + { + // create a new request with the final uri + request = request.CloneAndDispose(new global::System.Uri(_finalUri), Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + break; + } + } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response); + break; + } + case global::System.Net.HttpStatusCode.NoContent: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.Error.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// + /// Validation method for method. Call this like the actual call, but you will get + /// validation events back. + /// + /// The Microsoft Azure subscription ID. + /// The name of the resource group to which the container registry belongs. + /// The name of the configuration store. + /// an instance that will receive events. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresDelete_Validate(string subscriptionId, string resourceGroupName, string configStoreName, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(configStoreName),configStoreName); + await eventListener.AssertMinimumLength(nameof(configStoreName),configStoreName,5); + await eventListener.AssertMaximumLength(nameof(configStoreName),configStoreName,50); + await eventListener.AssertRegEx(nameof(configStoreName),configStoreName,@"^[a-zA-Z0-9_-]*$"); + } + } + + /// Gets the properties of the specified configuration store. + /// The Microsoft Azure subscription ID. + /// The name of the resource group to which the container registry belongs. + /// The name of the configuration store. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresGet(string subscriptionId, string resourceGroupName, string configStoreName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.AppConfiguration/configurationStores/" + + global::System.Uri.EscapeDataString(configStoreName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Gets the properties of the specified configuration store. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresGetViaIdentity(global::System.String viaIdentity, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.AppConfiguration/configurationStores/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var configStoreName = _match.Groups["configStoreName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.AppConfiguration/configurationStores/" + + configStoreName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresGet_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStore.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.Error.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// + /// Validation method for method. Call this like the actual call, but you will get validation + /// events back. + /// + /// The Microsoft Azure subscription ID. + /// The name of the resource group to which the container registry belongs. + /// The name of the configuration store. + /// an instance that will receive events. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresGet_Validate(string subscriptionId, string resourceGroupName, string configStoreName, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(configStoreName),configStoreName); + await eventListener.AssertMinimumLength(nameof(configStoreName),configStoreName,5); + await eventListener.AssertMaximumLength(nameof(configStoreName),configStoreName,50); + await eventListener.AssertRegEx(nameof(configStoreName),configStoreName,@"^[a-zA-Z0-9_-]*$"); + } + } + + /// Lists the configuration stores for a given subscription. + /// The Microsoft Azure subscription ID. + /// A skip token is used to continue retrieving items after an operation returns a partial result. + /// If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter + /// that specifies a starting point to use for subsequent calls. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresList(string subscriptionId, string SkipToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.AppConfiguration/configurationStores" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(SkipToken) ? global::System.String.Empty : "$skipToken=" + global::System.Uri.EscapeDataString(SkipToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresList_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Lists the configuration stores for a given resource group. + /// The Microsoft Azure subscription ID. + /// The name of the resource group to which the container registry belongs. + /// A skip token is used to continue retrieving items after an operation returns a partial result. + /// If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter + /// that specifies a starting point to use for subsequent calls. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresListByResourceGroup(string subscriptionId, string resourceGroupName, string SkipToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.AppConfiguration/configurationStores" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(SkipToken) ? global::System.String.Empty : "$skipToken=" + global::System.Uri.EscapeDataString(SkipToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresListByResourceGroup_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Lists the configuration stores for a given resource group. + /// + /// A skip token is used to continue retrieving items after an operation returns a partial result. + /// If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter + /// that specifies a starting point to use for subsequent calls. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresListByResourceGroupViaIdentity(global::System.String viaIdentity, string SkipToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.AppConfiguration/configurationStores$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.AppConfiguration/configurationStores" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(SkipToken) ? global::System.String.Empty : "$skipToken=" + global::System.Uri.EscapeDataString(SkipToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresListByResourceGroup_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresListByResourceGroup_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.Error.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// + /// Validation method for method. Call this like the actual call, but + /// you will get validation events back. + /// + /// The Microsoft Azure subscription ID. + /// The name of the resource group to which the container registry belongs. + /// A skip token is used to continue retrieving items after an operation returns a partial result. + /// If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter + /// that specifies a starting point to use for subsequent calls. + /// an instance that will receive events. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresListByResourceGroup_Validate(string subscriptionId, string resourceGroupName, string SkipToken, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(SkipToken),SkipToken); + } + } + + /// Lists a configuration store key-value. + /// The Microsoft Azure subscription ID. + /// The name of the resource group to which the container registry belongs. + /// The name of the configuration store. + /// The parameters for retrieving a key-value. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresListKeyValue(string subscriptionId, string resourceGroupName, string configStoreName, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.AppConfiguration/configurationStores/" + + global::System.Uri.EscapeDataString(configStoreName) + + "/listKeyValue" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresListKeyValue_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Lists a configuration store key-value. + /// + /// The parameters for retrieving a key-value. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresListKeyValueViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.AppConfiguration/configurationStores/(?[^/]+)/listKeyValue$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}/listKeyValue'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var configStoreName = _match.Groups["configStoreName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.AppConfiguration/configurationStores/" + + configStoreName + + "/listKeyValue" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresListKeyValue_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresListKeyValue_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.KeyValue.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.Error.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// + /// Validation method for method. Call this like the actual call, but you will + /// get validation events back. + /// + /// The Microsoft Azure subscription ID. + /// The name of the resource group to which the container registry belongs. + /// The name of the configuration store. + /// The parameters for retrieving a key-value. + /// an instance that will receive events. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresListKeyValue_Validate(string subscriptionId, string resourceGroupName, string configStoreName, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParameters body, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(configStoreName),configStoreName); + await eventListener.AssertMinimumLength(nameof(configStoreName),configStoreName,5); + await eventListener.AssertMaximumLength(nameof(configStoreName),configStoreName,50); + await eventListener.AssertRegEx(nameof(configStoreName),configStoreName,@"^[a-zA-Z0-9_-]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Lists the access key for the specified configuration store. + /// The Microsoft Azure subscription ID. + /// The name of the resource group to which the container registry belongs. + /// The name of the configuration store. + /// A skip token is used to continue retrieving items after an operation returns a partial result. + /// If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter + /// that specifies a starting point to use for subsequent calls. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresListKeys(string subscriptionId, string resourceGroupName, string configStoreName, string SkipToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.AppConfiguration/configurationStores/" + + global::System.Uri.EscapeDataString(configStoreName) + + "/ListKeys" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(SkipToken) ? global::System.String.Empty : "$skipToken=" + global::System.Uri.EscapeDataString(SkipToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresListKeys_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Lists the access key for the specified configuration store. + /// + /// A skip token is used to continue retrieving items after an operation returns a partial result. + /// If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter + /// that specifies a starting point to use for subsequent calls. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresListKeysViaIdentity(global::System.String viaIdentity, string SkipToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.AppConfiguration/configurationStores/(?[^/]+)/ListKeys$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}/ListKeys'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var configStoreName = _match.Groups["configStoreName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.AppConfiguration/configurationStores/" + + configStoreName + + "/ListKeys" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(SkipToken) ? global::System.String.Empty : "$skipToken=" + global::System.Uri.EscapeDataString(SkipToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresListKeys_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresListKeys_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ApiKeyListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.Error.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// + /// Validation method for method. Call this like the actual call, but you will + /// get validation events back. + /// + /// The Microsoft Azure subscription ID. + /// The name of the resource group to which the container registry belongs. + /// The name of the configuration store. + /// A skip token is used to continue retrieving items after an operation returns a partial result. + /// If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter + /// that specifies a starting point to use for subsequent calls. + /// an instance that will receive events. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresListKeys_Validate(string subscriptionId, string resourceGroupName, string configStoreName, string SkipToken, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(configStoreName),configStoreName); + await eventListener.AssertMinimumLength(nameof(configStoreName),configStoreName,5); + await eventListener.AssertMaximumLength(nameof(configStoreName),configStoreName,50); + await eventListener.AssertRegEx(nameof(configStoreName),configStoreName,@"^[a-zA-Z0-9_-]*$"); + await eventListener.AssertNotNull(nameof(SkipToken),SkipToken); + } + } + + /// Lists the configuration stores for a given subscription. + /// + /// A skip token is used to continue retrieving items after an operation returns a partial result. + /// If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter + /// that specifies a starting point to use for subsequent calls. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresListViaIdentity(global::System.String viaIdentity, string SkipToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.AppConfiguration/configurationStores$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.AppConfiguration/configurationStores'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/providers/Microsoft.AppConfiguration/configurationStores" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(SkipToken) ? global::System.String.Empty : "$skipToken=" + global::System.Uri.EscapeDataString(SkipToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresList_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresList_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.Error.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// + /// Validation method for method. Call this like the actual call, but you will get + /// validation events back. + /// + /// The Microsoft Azure subscription ID. + /// A skip token is used to continue retrieving items after an operation returns a partial result. + /// If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter + /// that specifies a starting point to use for subsequent calls. + /// an instance that will receive events. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresList_Validate(string subscriptionId, string SkipToken, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(SkipToken),SkipToken); + } + } + + /// Regenerates an access key for the specified configuration store. + /// The Microsoft Azure subscription ID. + /// The name of the resource group to which the container registry belongs. + /// The name of the configuration store. + /// The parameters for regenerating an access key. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresRegenerateKey(string subscriptionId, string resourceGroupName, string configStoreName, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.AppConfiguration/configurationStores/" + + global::System.Uri.EscapeDataString(configStoreName) + + "/RegenerateKey" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresRegenerateKey_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Regenerates an access key for the specified configuration store. + /// + /// The parameters for regenerating an access key. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresRegenerateKeyViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.AppConfiguration/configurationStores/(?[^/]+)/RegenerateKey$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}/RegenerateKey'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var configStoreName = _match.Groups["configStoreName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.AppConfiguration/configurationStores/" + + configStoreName + + "/RegenerateKey" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresRegenerateKey_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresRegenerateKey_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ApiKey.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.Error.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// + /// Validation method for method. Call this like the actual call, but you + /// will get validation events back. + /// + /// The Microsoft Azure subscription ID. + /// The name of the resource group to which the container registry belongs. + /// The name of the configuration store. + /// The parameters for regenerating an access key. + /// an instance that will receive events. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresRegenerateKey_Validate(string subscriptionId, string resourceGroupName, string configStoreName, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters body, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(configStoreName),configStoreName); + await eventListener.AssertMinimumLength(nameof(configStoreName),configStoreName,5); + await eventListener.AssertMaximumLength(nameof(configStoreName),configStoreName,50); + await eventListener.AssertRegEx(nameof(configStoreName),configStoreName,@"^[a-zA-Z0-9_-]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Updates a configuration store with the specified parameters. + /// The Microsoft Azure subscription ID. + /// The name of the resource group to which the container registry belongs. + /// The name of the configuration store. + /// The parameters for updating a configuration store. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresUpdate(string subscriptionId, string resourceGroupName, string configStoreName, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.AppConfiguration/configurationStores/" + + global::System.Uri.EscapeDataString(configStoreName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Updates a configuration store with the specified parameters. + /// + /// The parameters for updating a configuration store. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task ConfigurationStoresUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.AppConfiguration/configurationStores/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var configStoreName = _match.Groups["configStoreName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.AppConfiguration/configurationStores/" + + configStoreName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConfigurationStoresUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresUpdate_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + // declared final-state-via: default + var asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = _response.GetFirstHeader(@"Location"); + while (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + + // get the delay before polling. (default to 30 seconds if not present) + int delay = (int)(_response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.DelayBeforePolling, $"Delaying {delay} seconds before polling.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // start the delay timer (we'll await later...) + var waiting = global::System.Threading.Tasks.Task.Delay(delay * 1000, eventListener.Token ); + + // while we wait, let's grab the headers and get ready to poll. + if (!System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Azure-AsyncOperation"))) { + asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Location"))) { + location = _response.GetFirstHeader(@"Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? _originalUri : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get); + + // and let's look at the current response body and see if we have some information we can give back to the listener + var content = await _response.Content.ReadAsStringAsync(); + await waiting; + + // check for cancellation + if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Polling, $"Polling {_uri}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + try { + if( Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + var state = json.Property("properties")?.PropertyT("provisioningState") ?? json.PropertyT("status"); + if( state is null ) + { + // the body doesn't contain any information that has the state of the LRO + // we're going to just get out, and let the consumer have the result + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Polling, $"Polled {_uri} provisioning state {state}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + switch( state?.ToString()?.ToLower() ) + { + case "succeeded": + case "failed": + case "canceled": + // we're done polling. + break; + + default: + // need to keep polling! + _response.StatusCode = global::System.Net.HttpStatusCode.Created; + continue; + } + } + } catch { + // if we run into a problem peeking into the result, + // we really don't want to do anything special. + } + } + + // check for terminal status code + if (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + continue; + } + // we are done polling, do a request on final target? + if (!string.IsNullOrWhiteSpace(_originalUri)) + { + // create a new request with the final uri + request = request.CloneAndDispose(new global::System.Uri(_originalUri), Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + break; + } + } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStore.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.Error.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// + /// Validation method for method. Call this like the actual call, but you will get + /// validation events back. + /// + /// The Microsoft Azure subscription ID. + /// The name of the resource group to which the container registry belongs. + /// The name of the configuration store. + /// The parameters for updating a configuration store. + /// an instance that will receive events. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task ConfigurationStoresUpdate_Validate(string subscriptionId, string resourceGroupName, string configStoreName, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters body, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(configStoreName),configStoreName); + await eventListener.AssertMinimumLength(nameof(configStoreName),configStoreName,5); + await eventListener.AssertMaximumLength(nameof(configStoreName),configStoreName,50); + await eventListener.AssertRegEx(nameof(configStoreName),configStoreName,@"^[a-zA-Z0-9_-]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Checks whether the configuration store name is available for use. + /// The Microsoft Azure subscription ID. + /// The object containing information for the availability request. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationsCheckNameAvailability(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.AppConfiguration/checkNameAvailability" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsCheckNameAvailability_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Checks whether the configuration store name is available for use. + /// + /// The object containing information for the availability request. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationsCheckNameAvailabilityViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.AppConfiguration/checkNameAvailability$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.AppConfiguration/checkNameAvailability'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/providers/Microsoft.AppConfiguration/checkNameAvailability" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsCheckNameAvailability_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task OperationsCheckNameAvailability_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.NameAvailabilityStatus.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.Error.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// + /// Validation method for method. Call this like the actual call, but you will + /// get validation events back. + /// + /// The Microsoft Azure subscription ID. + /// The object containing information for the availability request. + /// an instance that will receive events. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task OperationsCheckNameAvailability_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters body, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Lists the operations available from this provider. + /// A skip token is used to continue retrieving items after an operation returns a partial result. + /// If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter + /// that specifies a starting point to use for subsequent calls. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationsList(string SkipToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/providers/Microsoft.AppConfiguration/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(SkipToken) ? global::System.String.Empty : "$skipToken=" + global::System.Uri.EscapeDataString(SkipToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Lists the operations available from this provider. + /// + /// A skip token is used to continue retrieving items after an operation returns a partial result. + /// If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter + /// that specifies a starting point to use for subsequent calls. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationsListViaIdentity(global::System.String viaIdentity, string SkipToken, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-02-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.AppConfiguration/operations$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.AppConfiguration/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/providers/Microsoft.AppConfiguration/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (string.IsNullOrEmpty(SkipToken) ? global::System.String.Empty : "$skipToken=" + global::System.Uri.EscapeDataString(SkipToken)) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task OperationsList_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.OperationDefinitionListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.Error.FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// + /// Validation method for method. Call this like the actual call, but you will get validation + /// events back. + /// + /// A skip token is used to continue retrieving items after an operation returns a partial result. + /// If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter + /// that specifies a starting point to use for subsequent calls. + /// an instance that will receive events. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task OperationsList_Validate(string SkipToken, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(SkipToken),SkipToken); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKey.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKey.PowerShell.cs new file mode 100644 index 000000000000..032436059c5c --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKey.PowerShell.cs @@ -0,0 +1,141 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// An API key used for authenticating with a configuration store endpoint. + [System.ComponentModel.TypeConverter(typeof(ApiKeyTypeConverter))] + public partial class ApiKey + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ApiKey(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).ConnectionString = (string) content.GetValueForProperty("ConnectionString",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).ConnectionString, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).LastModified = (global::System.DateTime?) content.GetValueForProperty("LastModified",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).LastModified, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).ReadOnly = (bool?) content.GetValueForProperty("ReadOnly",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).ReadOnly, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).Value = (string) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).Value, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ApiKey(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).ConnectionString = (string) content.GetValueForProperty("ConnectionString",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).ConnectionString, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).LastModified = (global::System.DateTime?) content.GetValueForProperty("LastModified",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).LastModified, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).ReadOnly = (bool?) content.GetValueForProperty("ReadOnly",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).ReadOnly, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).Value = (string) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal)this).Value, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ApiKey(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ApiKey(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// An API key used for authenticating with a configuration store endpoint. + [System.ComponentModel.TypeConverter(typeof(ApiKeyTypeConverter))] + public partial interface IApiKey + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKey.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKey.TypeConverter.cs new file mode 100644 index 000000000000..3a89702b011a --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKey.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ApiKeyTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ApiKey.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ApiKey.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ApiKey.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKey.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKey.cs new file mode 100644 index 000000000000..ea138f06544e --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKey.cs @@ -0,0 +1,149 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// An API key used for authenticating with a configuration store endpoint. + public partial class ApiKey : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal + { + + /// Backing field for property. + private string _connectionString; + + /// A connection string that can be used by supporting clients for authentication. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string ConnectionString { get => this._connectionString; } + + /// Backing field for property. + private string _id; + + /// The key ID. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Backing field for property. + private global::System.DateTime? _lastModified; + + /// The last time any of the key's properties were modified. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public global::System.DateTime? LastModified { get => this._lastModified; } + + /// Internal Acessors for ConnectionString + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal.ConnectionString { get => this._connectionString; set { {_connectionString = value;} } } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for LastModified + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal.LastModified { get => this._lastModified; set { {_lastModified = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for ReadOnly + bool? Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal.ReadOnly { get => this._readOnly; set { {_readOnly = value;} } } + + /// Internal Acessors for Value + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyInternal.Value { get => this._value; set { {_value = value;} } } + + /// Backing field for property. + private string _name; + + /// A name for the key describing its usage. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private bool? _readOnly; + + /// Whether this key can only be used for read operations. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public bool? ReadOnly { get => this._readOnly; } + + /// Backing field for property. + private string _value; + + /// The value of the key that is used for authentication purposes. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Value { get => this._value; } + + /// Creates an new instance. + public ApiKey() + { + + } + } + /// An API key used for authenticating with a configuration store endpoint. + public partial interface IApiKey : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable + { + /// A connection string that can be used by supporting clients for authentication. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"A connection string that can be used by supporting clients for authentication.", + SerializedName = @"connectionString", + PossibleTypes = new [] { typeof(string) })] + string ConnectionString { get; } + /// The key ID. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The key ID.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// The last time any of the key's properties were modified. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The last time any of the key's properties were modified.", + SerializedName = @"lastModified", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastModified { get; } + /// A name for the key describing its usage. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"A name for the key describing its usage.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// Whether this key can only be used for read operations. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Whether this key can only be used for read operations.", + SerializedName = @"readOnly", + PossibleTypes = new [] { typeof(bool) })] + bool? ReadOnly { get; } + /// The value of the key that is used for authentication purposes. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The value of the key that is used for authentication purposes.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(string) })] + string Value { get; } + + } + /// An API key used for authenticating with a configuration store endpoint. + internal partial interface IApiKeyInternal + + { + /// A connection string that can be used by supporting clients for authentication. + string ConnectionString { get; set; } + /// The key ID. + string Id { get; set; } + /// The last time any of the key's properties were modified. + global::System.DateTime? LastModified { get; set; } + /// A name for the key describing its usage. + string Name { get; set; } + /// Whether this key can only be used for read operations. + bool? ReadOnly { get; set; } + /// The value of the key that is used for authentication purposes. + string Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKey.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKey.json.cs new file mode 100644 index 000000000000..ef195b644f61 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKey.json.cs @@ -0,0 +1,129 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// An API key used for authenticating with a configuration store endpoint. + public partial class ApiKey + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal ApiKey(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_connectionString = If( json?.PropertyT("connectionString"), out var __jsonConnectionString) ? (string)__jsonConnectionString : (string)ConnectionString;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + {_lastModified = If( json?.PropertyT("lastModified"), out var __jsonLastModified) ? global::System.DateTime.TryParse((string)__jsonLastModified, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastModifiedValue) ? __jsonLastModifiedValue : LastModified : LastModified;} + {_readOnly = If( json?.PropertyT("readOnly"), out var __jsonReadOnly) ? (bool?)__jsonReadOnly : ReadOnly;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? (string)__jsonValue : (string)Value;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new ApiKey(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._connectionString)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._connectionString.ToString()) : null, "connectionString" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._lastModified ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._lastModified?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastModified" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._readOnly ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonBoolean((bool)this._readOnly) : null, "readOnly" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._value)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._value.ToString()) : null, "value" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKeyListResult.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKeyListResult.PowerShell.cs new file mode 100644 index 000000000000..4abcd5d528c0 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKeyListResult.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// The result of a request to list API keys. + [System.ComponentModel.TypeConverter(typeof(ApiKeyListResultTypeConverter))] + public partial class ApiKeyListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ApiKeyListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ApiKeyTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ApiKeyListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ApiKeyTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ApiKeyListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ApiKeyListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The result of a request to list API keys. + [System.ComponentModel.TypeConverter(typeof(ApiKeyListResultTypeConverter))] + public partial interface IApiKeyListResult + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKeyListResult.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKeyListResult.TypeConverter.cs new file mode 100644 index 000000000000..f97b0d0f3c8b --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKeyListResult.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ApiKeyListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ApiKeyListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ApiKeyListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ApiKeyListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKeyListResult.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKeyListResult.cs new file mode 100644 index 000000000000..e638948abf4c --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKeyListResult.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The result of a request to list API keys. + public partial class ApiKeyListResult : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResult, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The URI that can be used to request the next set of paged results. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey[] _value; + + /// The collection value. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ApiKeyListResult() + { + + } + } + /// The result of a request to list API keys. + public partial interface IApiKeyListResult : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable + { + /// The URI that can be used to request the next set of paged results. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The URI that can be used to request the next set of paged results.", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The collection value. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The collection value.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey) })] + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey[] Value { get; set; } + + } + /// The result of a request to list API keys. + internal partial interface IApiKeyListResultInternal + + { + /// The URI that can be used to request the next set of paged results. + string NextLink { get; set; } + /// The collection value. + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKeyListResult.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKeyListResult.json.cs new file mode 100644 index 000000000000..5af10a3b0466 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ApiKeyListResult.json.cs @@ -0,0 +1,111 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The result of a request to list API keys. + public partial class ApiKeyListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal ApiKeyListResult(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey) (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ApiKey.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKeyListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new ApiKeyListResult(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/CheckNameAvailabilityParameters.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/CheckNameAvailabilityParameters.PowerShell.cs new file mode 100644 index 000000000000..1044f8dc9c74 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/CheckNameAvailabilityParameters.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// Parameters used for checking whether a resource name is available. + [System.ComponentModel.TypeConverter(typeof(CheckNameAvailabilityParametersTypeConverter))] + public partial class CheckNameAvailabilityParameters + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CheckNameAvailabilityParameters(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParametersInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParametersInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParametersInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParametersInternal)this).Type, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CheckNameAvailabilityParameters(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParametersInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParametersInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParametersInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParametersInternal)this).Type, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CheckNameAvailabilityParameters(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CheckNameAvailabilityParameters(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Parameters used for checking whether a resource name is available. + [System.ComponentModel.TypeConverter(typeof(CheckNameAvailabilityParametersTypeConverter))] + public partial interface ICheckNameAvailabilityParameters + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/CheckNameAvailabilityParameters.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/CheckNameAvailabilityParameters.TypeConverter.cs new file mode 100644 index 000000000000..d8b30d8e9fe9 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/CheckNameAvailabilityParameters.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CheckNameAvailabilityParametersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CheckNameAvailabilityParameters.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CheckNameAvailabilityParameters.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CheckNameAvailabilityParameters.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/CheckNameAvailabilityParameters.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/CheckNameAvailabilityParameters.cs new file mode 100644 index 000000000000..3d4c1d7daf9e --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/CheckNameAvailabilityParameters.cs @@ -0,0 +1,66 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Parameters used for checking whether a resource name is available. + public partial class CheckNameAvailabilityParameters : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParametersInternal + { + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParametersInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// The name to check for availability. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _type= @"Microsoft.AppConfiguration/configurationStores"; + + /// The resource type to check for name availability. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public CheckNameAvailabilityParameters() + { + + } + } + /// Parameters used for checking whether a resource name is available. + public partial interface ICheckNameAvailabilityParameters : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable + { + /// The name to check for availability. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name to check for availability.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + /// The resource type to check for name availability. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = true, + Description = @"The resource type to check for name availability.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// Parameters used for checking whether a resource name is available. + internal partial interface ICheckNameAvailabilityParametersInternal + + { + /// The name to check for availability. + string Name { get; set; } + /// The resource type to check for name availability. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/CheckNameAvailabilityParameters.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/CheckNameAvailabilityParameters.json.cs new file mode 100644 index 000000000000..ddce1d6b2f9d --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/CheckNameAvailabilityParameters.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Parameters used for checking whether a resource name is available. + public partial class CheckNameAvailabilityParameters + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal CheckNameAvailabilityParameters(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)Type;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new CheckNameAvailabilityParameters(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStore.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStore.PowerShell.cs new file mode 100644 index 000000000000..1e18cf670762 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStore.PowerShell.cs @@ -0,0 +1,153 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// The configuration store along with all resource properties. The Configuration Store will have all information to begin + /// utilizing it. + /// + [System.ComponentModel.TypeConverter(typeof(ConfigurationStoreTypeConverter))] + public partial class ConfigurationStore + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ConfigurationStore(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStorePropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal)this).CreationDate = (global::System.DateTime?) content.GetValueForProperty("CreationDate",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal)this).CreationDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal)this).Endpoint = (string) content.GetValueForProperty("Endpoint",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal)this).Endpoint, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ConfigurationStore(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStorePropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal)this).CreationDate = (global::System.DateTime?) content.GetValueForProperty("CreationDate",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal)this).CreationDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal)this).Endpoint = (string) content.GetValueForProperty("Endpoint",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal)this).Endpoint, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ConfigurationStore(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ConfigurationStore(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The configuration store along with all resource properties. The Configuration Store will have all information to begin + /// utilizing it. + [System.ComponentModel.TypeConverter(typeof(ConfigurationStoreTypeConverter))] + public partial interface IConfigurationStore + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStore.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStore.TypeConverter.cs new file mode 100644 index 000000000000..275600487d86 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStore.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ConfigurationStoreTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ConfigurationStore.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ConfigurationStore.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ConfigurationStore.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStore.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStore.cs new file mode 100644 index 000000000000..bedddb0918ac --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStore.cs @@ -0,0 +1,147 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// + /// The configuration store along with all resource properties. The Configuration Store will have all information to begin + /// utilizing it. + /// + public partial class ConfigurationStore : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.Resource(); + + /// The creation date of configuration store. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Inlined)] + public global::System.DateTime? CreationDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)Property).CreationDate; } + + /// The DNS endpoint where the configuration store API will be available. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Inlined)] + public string Endpoint { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)Property).Endpoint; } + + /// The resource ID. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)__resource).Id; } + + /// + /// The location of the resource. This cannot be changed after the resource is created. + /// + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Inherited)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)__resource).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)__resource).Location = value; } + + /// Internal Acessors for CreationDate + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal.CreationDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)Property).CreationDate; set => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)Property).CreationDate = value; } + + /// Internal Acessors for Endpoint + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal.Endpoint { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)Property).Endpoint; set => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)Property).Endpoint = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreProperties Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState? Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)Property).ProvisioningState = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)__resource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)__resource).Name = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)__resource).Type = value; } + + /// The name of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)__resource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreProperties _property; + + /// The properties of a configuration store. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreProperties()); set => this._property = value; } + + /// The provisioning state of the configuration store. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState? ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)Property).ProvisioningState; } + + /// The tags of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)__resource).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)__resource).Tag = value; } + + /// The type of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)__resource).Type; } + + /// Creates an new instance. + public ConfigurationStore() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__resource), __resource); + await eventListener.AssertObjectIsValid(nameof(__resource), __resource); + } + } + /// The configuration store along with all resource properties. The Configuration Store will have all information to begin + /// utilizing it. + public partial interface IConfigurationStore : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResource + { + /// The creation date of configuration store. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The creation date of configuration store.", + SerializedName = @"creationDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? CreationDate { get; } + /// The DNS endpoint where the configuration store API will be available. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The DNS endpoint where the configuration store API will be available.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + string Endpoint { get; } + /// The provisioning state of the configuration store. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The provisioning state of the configuration store.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState) })] + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState? ProvisioningState { get; } + + } + /// The configuration store along with all resource properties. The Configuration Store will have all information to begin + /// utilizing it. + internal partial interface IConfigurationStoreInternal : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal + { + /// The creation date of configuration store. + global::System.DateTime? CreationDate { get; set; } + /// The DNS endpoint where the configuration store API will be available. + string Endpoint { get; set; } + /// The properties of a configuration store. + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreProperties Property { get; set; } + /// The provisioning state of the configuration store. + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState? ProvisioningState { get; set; } + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStore.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStore.json.cs new file mode 100644 index 000000000000..d9e878061609 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStore.json.cs @@ -0,0 +1,106 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// + /// The configuration store along with all resource properties. The Configuration Store will have all information to begin + /// utilizing it. + /// + public partial class ConfigurationStore + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal ConfigurationStore(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.Resource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreProperties.FromJson(__jsonProperties) : Property;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new ConfigurationStore(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __resource?.ToJson(container, serializationMode); + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreListResult.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreListResult.PowerShell.cs new file mode 100644 index 000000000000..97cbba93c49e --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreListResult.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// The result of a request to list configuration stores. + [System.ComponentModel.TypeConverter(typeof(ConfigurationStoreListResultTypeConverter))] + public partial class ConfigurationStoreListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ConfigurationStoreListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ConfigurationStoreListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ConfigurationStoreListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ConfigurationStoreListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The result of a request to list configuration stores. + [System.ComponentModel.TypeConverter(typeof(ConfigurationStoreListResultTypeConverter))] + public partial interface IConfigurationStoreListResult + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreListResult.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreListResult.TypeConverter.cs new file mode 100644 index 000000000000..afd0b3c9eac0 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreListResult.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ConfigurationStoreListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ConfigurationStoreListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ConfigurationStoreListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ConfigurationStoreListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreListResult.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreListResult.cs new file mode 100644 index 000000000000..de7e96a3eb8d --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreListResult.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The result of a request to list configuration stores. + public partial class ConfigurationStoreListResult : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResult, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The URI that can be used to request the next set of paged results. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore[] _value; + + /// The collection value. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ConfigurationStoreListResult() + { + + } + } + /// The result of a request to list configuration stores. + public partial interface IConfigurationStoreListResult : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable + { + /// The URI that can be used to request the next set of paged results. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The URI that can be used to request the next set of paged results.", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The collection value. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The collection value.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore) })] + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore[] Value { get; set; } + + } + /// The result of a request to list configuration stores. + internal partial interface IConfigurationStoreListResultInternal + + { + /// The URI that can be used to request the next set of paged results. + string NextLink { get; set; } + /// The collection value. + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreListResult.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreListResult.json.cs new file mode 100644 index 000000000000..c4c01832fff6 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreListResult.json.cs @@ -0,0 +1,111 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The result of a request to list configuration stores. + public partial class ConfigurationStoreListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal ConfigurationStoreListResult(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore) (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStore.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new ConfigurationStoreListResult(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreProperties.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreProperties.PowerShell.cs new file mode 100644 index 000000000000..a8a573c796fe --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreProperties.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// The properties of a configuration store. + [System.ComponentModel.TypeConverter(typeof(ConfigurationStorePropertiesTypeConverter))] + public partial class ConfigurationStoreProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ConfigurationStoreProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)this).CreationDate = (global::System.DateTime?) content.GetValueForProperty("CreationDate",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)this).CreationDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)this).Endpoint = (string) content.GetValueForProperty("Endpoint",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)this).Endpoint, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState.CreateFrom); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ConfigurationStoreProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)this).CreationDate = (global::System.DateTime?) content.GetValueForProperty("CreationDate",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)this).CreationDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)this).Endpoint = (string) content.GetValueForProperty("Endpoint",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)this).Endpoint, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState.CreateFrom); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ConfigurationStoreProperties(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ConfigurationStoreProperties(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The properties of a configuration store. + [System.ComponentModel.TypeConverter(typeof(ConfigurationStorePropertiesTypeConverter))] + public partial interface IConfigurationStoreProperties + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreProperties.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreProperties.TypeConverter.cs new file mode 100644 index 000000000000..3bcd13d1a20b --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreProperties.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ConfigurationStorePropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ConfigurationStoreProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ConfigurationStoreProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ConfigurationStoreProperties.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreProperties.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreProperties.cs new file mode 100644 index 000000000000..1bde6a6f7316 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreProperties.cs @@ -0,0 +1,89 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The properties of a configuration store. + public partial class ConfigurationStoreProperties : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreProperties, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal + { + + /// Backing field for property. + private global::System.DateTime? _creationDate; + + /// The creation date of configuration store. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public global::System.DateTime? CreationDate { get => this._creationDate; } + + /// Backing field for property. + private string _endpoint; + + /// The DNS endpoint where the configuration store API will be available. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Endpoint { get => this._endpoint; } + + /// Internal Acessors for CreationDate + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal.CreationDate { get => this._creationDate; set { {_creationDate = value;} } } + + /// Internal Acessors for Endpoint + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal.Endpoint { get => this._endpoint; set { {_endpoint = value;} } } + + /// Internal Acessors for ProvisioningState + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState? Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState? _provisioningState; + + /// The provisioning state of the configuration store. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState? ProvisioningState { get => this._provisioningState; } + + /// Creates an new instance. + public ConfigurationStoreProperties() + { + + } + } + /// The properties of a configuration store. + public partial interface IConfigurationStoreProperties : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable + { + /// The creation date of configuration store. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The creation date of configuration store.", + SerializedName = @"creationDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? CreationDate { get; } + /// The DNS endpoint where the configuration store API will be available. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The DNS endpoint where the configuration store API will be available.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + string Endpoint { get; } + /// The provisioning state of the configuration store. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The provisioning state of the configuration store.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState) })] + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState? ProvisioningState { get; } + + } + /// The properties of a configuration store. + internal partial interface IConfigurationStorePropertiesInternal + + { + /// The creation date of configuration store. + global::System.DateTime? CreationDate { get; set; } + /// The DNS endpoint where the configuration store API will be available. + string Endpoint { get; set; } + /// The provisioning state of the configuration store. + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState? ProvisioningState { get; set; } + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreProperties.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreProperties.json.cs new file mode 100644 index 000000000000..e3ec84a9360b --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreProperties.json.cs @@ -0,0 +1,114 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The properties of a configuration store. + public partial class ConfigurationStoreProperties + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal ConfigurationStoreProperties(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_creationDate = If( json?.PropertyT("creationDate"), out var __jsonCreationDate) ? global::System.DateTime.TryParse((string)__jsonCreationDate, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonCreationDateValue) ? __jsonCreationDateValue : CreationDate : CreationDate;} + {_endpoint = If( json?.PropertyT("endpoint"), out var __jsonEndpoint) ? (string)__jsonEndpoint : (string)Endpoint;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)ProvisioningState;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new ConfigurationStoreProperties(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._creationDate ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._creationDate?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "creationDate" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._endpoint)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._endpoint.ToString()) : null, "endpoint" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStorePropertiesUpdateParameters.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStorePropertiesUpdateParameters.PowerShell.cs new file mode 100644 index 000000000000..31589f23ebba --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStorePropertiesUpdateParameters.PowerShell.cs @@ -0,0 +1,132 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// The properties for updating a configuration store. + [System.ComponentModel.TypeConverter(typeof(ConfigurationStorePropertiesUpdateParametersTypeConverter))] + public partial class ConfigurationStorePropertiesUpdateParameters + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ConfigurationStorePropertiesUpdateParameters(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ConfigurationStorePropertiesUpdateParameters(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ConfigurationStorePropertiesUpdateParameters(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ConfigurationStorePropertiesUpdateParameters(content); + } + + /// + /// Creates a new instance of , deserializing the content from + /// a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The properties for updating a configuration store. + [System.ComponentModel.TypeConverter(typeof(ConfigurationStorePropertiesUpdateParametersTypeConverter))] + public partial interface IConfigurationStorePropertiesUpdateParameters + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStorePropertiesUpdateParameters.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStorePropertiesUpdateParameters.TypeConverter.cs new file mode 100644 index 000000000000..bf8c1112b434 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStorePropertiesUpdateParameters.TypeConverter.cs @@ -0,0 +1,145 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ConfigurationStorePropertiesUpdateParametersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, + /// otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ConfigurationStorePropertiesUpdateParameters.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ConfigurationStorePropertiesUpdateParameters.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ConfigurationStorePropertiesUpdateParameters.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStorePropertiesUpdateParameters.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStorePropertiesUpdateParameters.cs new file mode 100644 index 000000000000..0ac8079d830b --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStorePropertiesUpdateParameters.cs @@ -0,0 +1,31 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The properties for updating a configuration store. + public partial class ConfigurationStorePropertiesUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParametersInternal + { + + /// + /// Creates an new instance. + /// + public ConfigurationStorePropertiesUpdateParameters() + { + + } + } + /// The properties for updating a configuration store. + public partial interface IConfigurationStorePropertiesUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable + { + + } + /// The properties for updating a configuration store. + internal partial interface IConfigurationStorePropertiesUpdateParametersInternal + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStorePropertiesUpdateParameters.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStorePropertiesUpdateParameters.json.cs new file mode 100644 index 000000000000..ac183fb4d3db --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStorePropertiesUpdateParameters.json.cs @@ -0,0 +1,102 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The properties for updating a configuration store. + public partial class ConfigurationStorePropertiesUpdateParameters + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal ConfigurationStorePropertiesUpdateParameters(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new ConfigurationStorePropertiesUpdateParameters(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParameters.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParameters.PowerShell.cs new file mode 100644 index 000000000000..4669fdf4184e --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParameters.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// The parameters for updating a configuration store. + [System.ComponentModel.TypeConverter(typeof(ConfigurationStoreUpdateParametersTypeConverter))] + public partial class ConfigurationStoreUpdateParameters + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ConfigurationStoreUpdateParameters(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStorePropertiesUpdateParametersTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreUpdateParametersTagsTypeConverter.ConvertFrom); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ConfigurationStoreUpdateParameters(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStorePropertiesUpdateParametersTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreUpdateParametersTagsTypeConverter.ConvertFrom); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ConfigurationStoreUpdateParameters(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ConfigurationStoreUpdateParameters(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The parameters for updating a configuration store. + [System.ComponentModel.TypeConverter(typeof(ConfigurationStoreUpdateParametersTypeConverter))] + public partial interface IConfigurationStoreUpdateParameters + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParameters.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParameters.TypeConverter.cs new file mode 100644 index 000000000000..3ca13cfb6cf8 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParameters.TypeConverter.cs @@ -0,0 +1,143 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ConfigurationStoreUpdateParametersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise + /// false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ConfigurationStoreUpdateParameters.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ConfigurationStoreUpdateParameters.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ConfigurationStoreUpdateParameters.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParameters.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParameters.cs new file mode 100644 index 000000000000..9e79792bad11 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParameters.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The parameters for updating a configuration store. + public partial class ConfigurationStoreUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters _property; + + /// The properties for updating a configuration store. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStorePropertiesUpdateParameters()); set => this._property = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags _tag; + + /// The ARM resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreUpdateParametersTags()); set => this._tag = value; } + + /// Creates an new instance. + public ConfigurationStoreUpdateParameters() + { + + } + } + /// The parameters for updating a configuration store. + public partial interface IConfigurationStoreUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable + { + /// The properties for updating a configuration store. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The properties for updating a configuration store.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters) })] + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters Property { get; set; } + /// The ARM resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The ARM resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags) })] + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags Tag { get; set; } + + } + /// The parameters for updating a configuration store. + internal partial interface IConfigurationStoreUpdateParametersInternal + + { + /// The properties for updating a configuration store. + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters Property { get; set; } + /// The ARM resource tags. + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParameters.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParameters.json.cs new file mode 100644 index 000000000000..08104b722a8e --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParameters.json.cs @@ -0,0 +1,104 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The parameters for updating a configuration store. + public partial class ConfigurationStoreUpdateParameters + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal ConfigurationStoreUpdateParameters(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStorePropertiesUpdateParameters.FromJson(__jsonProperties) : Property;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreUpdateParametersTags.FromJson(__jsonTags) : Tag;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new ConfigurationStoreUpdateParameters(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParametersTags.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParametersTags.PowerShell.cs new file mode 100644 index 000000000000..8adc6176767d --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParametersTags.PowerShell.cs @@ -0,0 +1,136 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// The ARM resource tags. + [System.ComponentModel.TypeConverter(typeof(ConfigurationStoreUpdateParametersTagsTypeConverter))] + public partial class ConfigurationStoreUpdateParametersTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ConfigurationStoreUpdateParametersTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ConfigurationStoreUpdateParametersTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ConfigurationStoreUpdateParametersTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ConfigurationStoreUpdateParametersTags(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json + /// string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The ARM resource tags. + [System.ComponentModel.TypeConverter(typeof(ConfigurationStoreUpdateParametersTagsTypeConverter))] + public partial interface IConfigurationStoreUpdateParametersTags + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParametersTags.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParametersTags.TypeConverter.cs new file mode 100644 index 000000000000..8a48c555bdc0 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParametersTags.TypeConverter.cs @@ -0,0 +1,145 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ConfigurationStoreUpdateParametersTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise + /// false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ConfigurationStoreUpdateParametersTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ConfigurationStoreUpdateParametersTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ConfigurationStoreUpdateParametersTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParametersTags.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParametersTags.cs new file mode 100644 index 000000000000..c78b64da88b2 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParametersTags.cs @@ -0,0 +1,30 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The ARM resource tags. + public partial class ConfigurationStoreUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTagsInternal + { + + /// Creates an new instance. + public ConfigurationStoreUpdateParametersTags() + { + + } + } + /// The ARM resource tags. + public partial interface IConfigurationStoreUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray + { + + } + /// The ARM resource tags. + internal partial interface IConfigurationStoreUpdateParametersTagsInternal + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParametersTags.dictionary.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParametersTags.dictionary.cs new file mode 100644 index 000000000000..632f786d5a89 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParametersTags.dictionary.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + public partial class ConfigurationStoreUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); + + public void Clear() => __additionalProperties.Clear(); + + /// + public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); + + /// + public void CopyFrom(global::System.Collections.IDictionary source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public void CopyFrom(global::System.Management.Automation.PSObject source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public bool Remove(global::System.String key) => __additionalProperties.Remove( key); + + /// + /// + public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreUpdateParametersTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParametersTags.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParametersTags.json.cs new file mode 100644 index 000000000000..07849182ed9c --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ConfigurationStoreUpdateParametersTags.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The ARM resource tags. + public partial class ConfigurationStoreUpdateParametersTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + /// + internal ConfigurationStoreUpdateParametersTags(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet exclusions = null) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new ConfigurationStoreUpdateParametersTags(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/Error.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/Error.PowerShell.cs new file mode 100644 index 000000000000..05e583add9a4 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/Error.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// AppConfiguration error object. + [System.ComponentModel.TypeConverter(typeof(ErrorTypeConverter))] + public partial class Error + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IError DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Error(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IError DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Error(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Error(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IErrorInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IErrorInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IErrorInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IErrorInternal)this).Message, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Error(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IErrorInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IErrorInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IErrorInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IErrorInternal)this).Message, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IError FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// AppConfiguration error object. + [System.ComponentModel.TypeConverter(typeof(ErrorTypeConverter))] + public partial interface IError + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/Error.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/Error.TypeConverter.cs new file mode 100644 index 000000000000..c6ff71d7864a --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/Error.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IError ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IError).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Error.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Error.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Error.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/Error.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/Error.cs new file mode 100644 index 000000000000..79c4cda6e790 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/Error.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// AppConfiguration error object. + public partial class Error : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IError, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IErrorInternal + { + + /// Backing field for property. + private string _code; + + /// Error code. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Code { get => this._code; set => this._code = value; } + + /// Backing field for property. + private string _message; + + /// Error message. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Message { get => this._message; set => this._message = value; } + + /// Creates an new instance. + public Error() + { + + } + } + /// AppConfiguration error object. + public partial interface IError : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable + { + /// Error code. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; set; } + /// Error message. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; set; } + + } + /// AppConfiguration error object. + internal partial interface IErrorInternal + + { + /// Error code. + string Code { get; set; } + /// Error message. + string Message { get; set; } + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/Error.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/Error.json.cs new file mode 100644 index 000000000000..c97275645eee --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/Error.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// AppConfiguration error object. + public partial class Error + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal Error(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_code = If( json?.PropertyT("code"), out var __jsonCode) ? (string)__jsonCode : (string)Code;} + {_message = If( json?.PropertyT("message"), out var __jsonMessage) ? (string)__jsonMessage : (string)Message;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IError. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IError. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IError FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new Error(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValue.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValue.PowerShell.cs new file mode 100644 index 000000000000..9983e72c3e5b --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValue.PowerShell.cs @@ -0,0 +1,147 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// The result of a request to retrieve a key-value from the specified configuration store. + /// + [System.ComponentModel.TypeConverter(typeof(KeyValueTypeConverter))] + public partial class KeyValue + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValue DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new KeyValue(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValue DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new KeyValue(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValue FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal KeyValue(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).ContentType = (string) content.GetValueForProperty("ContentType",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).ContentType, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).ETag = (string) content.GetValueForProperty("ETag",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).ETag, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Key = (string) content.GetValueForProperty("Key",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Key, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Label = (string) content.GetValueForProperty("Label",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Label, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).LastModified = (global::System.DateTime?) content.GetValueForProperty("LastModified",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).LastModified, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Locked = (bool?) content.GetValueForProperty("Locked",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Locked, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.KeyValueTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Value = (string) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Value, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal KeyValue(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).ContentType = (string) content.GetValueForProperty("ContentType",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).ContentType, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).ETag = (string) content.GetValueForProperty("ETag",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).ETag, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Key = (string) content.GetValueForProperty("Key",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Key, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Label = (string) content.GetValueForProperty("Label",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Label, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).LastModified = (global::System.DateTime?) content.GetValueForProperty("LastModified",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).LastModified, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Locked = (bool?) content.GetValueForProperty("Locked",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Locked, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.KeyValueTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Value = (string) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal)this).Value, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The result of a request to retrieve a key-value from the specified configuration store. + [System.ComponentModel.TypeConverter(typeof(KeyValueTypeConverter))] + public partial interface IKeyValue + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValue.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValue.TypeConverter.cs new file mode 100644 index 000000000000..a72a93ba9f49 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValue.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class KeyValueTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValue ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValue).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return KeyValue.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return KeyValue.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return KeyValue.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValue.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValue.cs new file mode 100644 index 000000000000..5178bb9da421 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValue.cs @@ -0,0 +1,237 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// + /// The result of a request to retrieve a key-value from the specified configuration store. + /// + public partial class KeyValue : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValue, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal + { + + /// Backing field for property. + private string _contentType; + + /// + /// The content type of the key-value's value. + /// Providing a proper content-type can enable transformations of values when they are retrieved by applications. + /// + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string ContentType { get => this._contentType; } + + /// Backing field for property. + private string _eTag; + + /// An ETag indicating the state of a key-value within a configuration store. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string ETag { get => this._eTag; } + + /// Backing field for property. + private string _key; + + /// + /// The primary identifier of a key-value. + /// The key is used in unison with the label to uniquely identify a key-value. + /// + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Key { get => this._key; } + + /// Backing field for property. + private string _label; + + /// + /// A value used to group key-values. + /// The label is used in unison with the key to uniquely identify a key-value. + /// + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Label { get => this._label; } + + /// Backing field for property. + private global::System.DateTime? _lastModified; + + /// The last time a modifying operation was performed on the given key-value. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public global::System.DateTime? LastModified { get => this._lastModified; } + + /// Backing field for property. + private bool? _locked; + + /// + /// A value indicating whether the key-value is locked. + /// A locked key-value may not be modified until it is unlocked. + /// + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public bool? Locked { get => this._locked; } + + /// Internal Acessors for ContentType + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal.ContentType { get => this._contentType; set { {_contentType = value;} } } + + /// Internal Acessors for ETag + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal.ETag { get => this._eTag; set { {_eTag = value;} } } + + /// Internal Acessors for Key + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal.Key { get => this._key; set { {_key = value;} } } + + /// Internal Acessors for Label + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal.Label { get => this._label; set { {_label = value;} } } + + /// Internal Acessors for LastModified + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal.LastModified { get => this._lastModified; set { {_lastModified = value;} } } + + /// Internal Acessors for Locked + bool? Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal.Locked { get => this._locked; set { {_locked = value;} } } + + /// Internal Acessors for Tag + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTags Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal.Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.KeyValueTags()); set { {_tag = value;} } } + + /// Internal Acessors for Value + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueInternal.Value { get => this._value; set { {_value = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTags _tag; + + /// + /// A dictionary of tags that can help identify what a key-value may be applicable for. + /// + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.KeyValueTags()); } + + /// Backing field for property. + private string _value; + + /// The value of the key-value. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Value { get => this._value; } + + /// Creates an new instance. + public KeyValue() + { + + } + } + /// The result of a request to retrieve a key-value from the specified configuration store. + public partial interface IKeyValue : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable + { + /// + /// The content type of the key-value's value. + /// Providing a proper content-type can enable transformations of values when they are retrieved by applications. + /// + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The content type of the key-value's value. + Providing a proper content-type can enable transformations of values when they are retrieved by applications.", + SerializedName = @"contentType", + PossibleTypes = new [] { typeof(string) })] + string ContentType { get; } + /// An ETag indicating the state of a key-value within a configuration store. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"An ETag indicating the state of a key-value within a configuration store.", + SerializedName = @"eTag", + PossibleTypes = new [] { typeof(string) })] + string ETag { get; } + /// + /// The primary identifier of a key-value. + /// The key is used in unison with the label to uniquely identify a key-value. + /// + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The primary identifier of a key-value. + The key is used in unison with the label to uniquely identify a key-value.", + SerializedName = @"key", + PossibleTypes = new [] { typeof(string) })] + string Key { get; } + /// + /// A value used to group key-values. + /// The label is used in unison with the key to uniquely identify a key-value. + /// + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"A value used to group key-values. + The label is used in unison with the key to uniquely identify a key-value.", + SerializedName = @"label", + PossibleTypes = new [] { typeof(string) })] + string Label { get; } + /// The last time a modifying operation was performed on the given key-value. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The last time a modifying operation was performed on the given key-value.", + SerializedName = @"lastModified", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastModified { get; } + /// + /// A value indicating whether the key-value is locked. + /// A locked key-value may not be modified until it is unlocked. + /// + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"A value indicating whether the key-value is locked. + A locked key-value may not be modified until it is unlocked.", + SerializedName = @"locked", + PossibleTypes = new [] { typeof(bool) })] + bool? Locked { get; } + /// + /// A dictionary of tags that can help identify what a key-value may be applicable for. + /// + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"A dictionary of tags that can help identify what a key-value may be applicable for.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTags) })] + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTags Tag { get; } + /// The value of the key-value. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The value of the key-value.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(string) })] + string Value { get; } + + } + /// The result of a request to retrieve a key-value from the specified configuration store. + internal partial interface IKeyValueInternal + + { + /// + /// The content type of the key-value's value. + /// Providing a proper content-type can enable transformations of values when they are retrieved by applications. + /// + string ContentType { get; set; } + /// An ETag indicating the state of a key-value within a configuration store. + string ETag { get; set; } + /// + /// The primary identifier of a key-value. + /// The key is used in unison with the label to uniquely identify a key-value. + /// + string Key { get; set; } + /// + /// A value used to group key-values. + /// The label is used in unison with the key to uniquely identify a key-value. + /// + string Label { get; set; } + /// The last time a modifying operation was performed on the given key-value. + global::System.DateTime? LastModified { get; set; } + /// + /// A value indicating whether the key-value is locked. + /// A locked key-value may not be modified until it is unlocked. + /// + bool? Locked { get; set; } + /// + /// A dictionary of tags that can help identify what a key-value may be applicable for. + /// + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTags Tag { get; set; } + /// The value of the key-value. + string Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValue.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValue.json.cs new file mode 100644 index 000000000000..1b43c4733017 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValue.json.cs @@ -0,0 +1,141 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// + /// The result of a request to retrieve a key-value from the specified configuration store. + /// + public partial class KeyValue + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValue. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValue. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValue FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new KeyValue(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal KeyValue(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_contentType = If( json?.PropertyT("contentType"), out var __jsonContentType) ? (string)__jsonContentType : (string)ContentType;} + {_eTag = If( json?.PropertyT("eTag"), out var __jsonETag) ? (string)__jsonETag : (string)ETag;} + {_key = If( json?.PropertyT("key"), out var __jsonKey) ? (string)__jsonKey : (string)Key;} + {_label = If( json?.PropertyT("label"), out var __jsonLabel) ? (string)__jsonLabel : (string)Label;} + {_lastModified = If( json?.PropertyT("lastModified"), out var __jsonLastModified) ? global::System.DateTime.TryParse((string)__jsonLastModified, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastModifiedValue) ? __jsonLastModifiedValue : LastModified : LastModified;} + {_locked = If( json?.PropertyT("locked"), out var __jsonLocked) ? (bool?)__jsonLocked : Locked;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.KeyValueTags.FromJson(__jsonTags) : Tag;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? (string)__jsonValue : (string)Value;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._contentType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._contentType.ToString()) : null, "contentType" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._eTag)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._eTag.ToString()) : null, "eTag" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._key)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._key.ToString()) : null, "key" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._label)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._label.ToString()) : null, "label" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._lastModified ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._lastModified?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastModified" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._locked ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonBoolean((bool)this._locked) : null, "locked" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._value)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._value.ToString()) : null, "value" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValueTags.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValueTags.PowerShell.cs new file mode 100644 index 000000000000..97aa5e96ab99 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValueTags.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A dictionary of tags that can help identify what a key-value may be applicable for. + /// + [System.ComponentModel.TypeConverter(typeof(KeyValueTagsTypeConverter))] + public partial class KeyValueTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new KeyValueTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new KeyValueTags(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal KeyValueTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal KeyValueTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// A dictionary of tags that can help identify what a key-value may be applicable for. + [System.ComponentModel.TypeConverter(typeof(KeyValueTagsTypeConverter))] + public partial interface IKeyValueTags + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValueTags.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValueTags.TypeConverter.cs new file mode 100644 index 000000000000..569dcc735819 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValueTags.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class KeyValueTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return KeyValueTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return KeyValueTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return KeyValueTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValueTags.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValueTags.cs new file mode 100644 index 000000000000..9e7be381c72f --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValueTags.cs @@ -0,0 +1,32 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// + /// A dictionary of tags that can help identify what a key-value may be applicable for. + /// + public partial class KeyValueTags : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTags, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTagsInternal + { + + /// Creates an new instance. + public KeyValueTags() + { + + } + } + /// A dictionary of tags that can help identify what a key-value may be applicable for. + public partial interface IKeyValueTags : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray + { + + } + /// A dictionary of tags that can help identify what a key-value may be applicable for. + internal partial interface IKeyValueTagsInternal + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValueTags.dictionary.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValueTags.dictionary.cs new file mode 100644 index 000000000000..43ccfde0cace --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValueTags.dictionary.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + public partial class KeyValueTags : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); + + public void Clear() => __additionalProperties.Clear(); + + /// + public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); + + /// + public void CopyFrom(global::System.Collections.IDictionary source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public void CopyFrom(global::System.Management.Automation.PSObject source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public bool Remove(global::System.String key) => __additionalProperties.Remove( key); + + /// + /// + public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.KeyValueTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValueTags.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValueTags.json.cs new file mode 100644 index 000000000000..d5f8514d2a0b --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/KeyValueTags.json.cs @@ -0,0 +1,104 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// + /// A dictionary of tags that can help identify what a key-value may be applicable for. + /// + public partial class KeyValueTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IKeyValueTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new KeyValueTags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + /// + internal KeyValueTags(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet exclusions = null) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ListKeyValueParameters.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ListKeyValueParameters.PowerShell.cs new file mode 100644 index 000000000000..e3146be971ba --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ListKeyValueParameters.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// The parameters used to list a configuration store key-value + [System.ComponentModel.TypeConverter(typeof(ListKeyValueParametersTypeConverter))] + public partial class ListKeyValueParameters + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParameters DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ListKeyValueParameters(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParameters DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ListKeyValueParameters(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParameters FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ListKeyValueParameters(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParametersInternal)this).Key = (string) content.GetValueForProperty("Key",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParametersInternal)this).Key, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParametersInternal)this).Label = (string) content.GetValueForProperty("Label",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParametersInternal)this).Label, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ListKeyValueParameters(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParametersInternal)this).Key = (string) content.GetValueForProperty("Key",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParametersInternal)this).Key, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParametersInternal)this).Label = (string) content.GetValueForProperty("Label",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParametersInternal)this).Label, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The parameters used to list a configuration store key-value + [System.ComponentModel.TypeConverter(typeof(ListKeyValueParametersTypeConverter))] + public partial interface IListKeyValueParameters + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ListKeyValueParameters.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ListKeyValueParameters.TypeConverter.cs new file mode 100644 index 000000000000..5e01ad3cf1ee --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ListKeyValueParameters.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ListKeyValueParametersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParameters ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParameters).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ListKeyValueParameters.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ListKeyValueParameters.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ListKeyValueParameters.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ListKeyValueParameters.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ListKeyValueParameters.cs new file mode 100644 index 000000000000..211848576cde --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ListKeyValueParameters.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The parameters used to list a configuration store key-value + public partial class ListKeyValueParameters : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParameters, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParametersInternal + { + + /// Backing field for property. + private string _key; + + /// The key to retrieve. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Key { get => this._key; set => this._key = value; } + + /// Backing field for property. + private string _label; + + /// The label of the key. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Label { get => this._label; set => this._label = value; } + + /// Creates an new instance. + public ListKeyValueParameters() + { + + } + } + /// The parameters used to list a configuration store key-value + public partial interface IListKeyValueParameters : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable + { + /// The key to retrieve. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The key to retrieve.", + SerializedName = @"key", + PossibleTypes = new [] { typeof(string) })] + string Key { get; set; } + /// The label of the key. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The label of the key.", + SerializedName = @"label", + PossibleTypes = new [] { typeof(string) })] + string Label { get; set; } + + } + /// The parameters used to list a configuration store key-value + internal partial interface IListKeyValueParametersInternal + + { + /// The key to retrieve. + string Key { get; set; } + /// The label of the key. + string Label { get; set; } + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ListKeyValueParameters.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ListKeyValueParameters.json.cs new file mode 100644 index 000000000000..e6754182b853 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ListKeyValueParameters.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The parameters used to list a configuration store key-value + public partial class ListKeyValueParameters + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParameters. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParameters. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IListKeyValueParameters FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new ListKeyValueParameters(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal ListKeyValueParameters(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_key = If( json?.PropertyT("key"), out var __jsonKey) ? (string)__jsonKey : (string)Key;} + {_label = If( json?.PropertyT("label"), out var __jsonLabel) ? (string)__jsonLabel : (string)Label;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._key)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._key.ToString()) : null, "key" ,container.Add ); + AddIf( null != (((object)this._label)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._label.ToString()) : null, "label" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/NameAvailabilityStatus.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/NameAvailabilityStatus.PowerShell.cs new file mode 100644 index 000000000000..3ca10fe67eca --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/NameAvailabilityStatus.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// The result of a request to check the availability of a resource name. + [System.ComponentModel.TypeConverter(typeof(NameAvailabilityStatusTypeConverter))] + public partial class NameAvailabilityStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new NameAvailabilityStatus(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new NameAvailabilityStatus(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal NameAvailabilityStatus(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatusInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatusInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatusInternal)this).NameAvailable = (bool?) content.GetValueForProperty("NameAvailable",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatusInternal)this).NameAvailable, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatusInternal)this).Reason = (string) content.GetValueForProperty("Reason",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatusInternal)this).Reason, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal NameAvailabilityStatus(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatusInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatusInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatusInternal)this).NameAvailable = (bool?) content.GetValueForProperty("NameAvailable",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatusInternal)this).NameAvailable, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatusInternal)this).Reason = (string) content.GetValueForProperty("Reason",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatusInternal)this).Reason, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The result of a request to check the availability of a resource name. + [System.ComponentModel.TypeConverter(typeof(NameAvailabilityStatusTypeConverter))] + public partial interface INameAvailabilityStatus + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/NameAvailabilityStatus.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/NameAvailabilityStatus.TypeConverter.cs new file mode 100644 index 000000000000..b5ba625b6a94 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/NameAvailabilityStatus.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class NameAvailabilityStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return NameAvailabilityStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return NameAvailabilityStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return NameAvailabilityStatus.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/NameAvailabilityStatus.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/NameAvailabilityStatus.cs new file mode 100644 index 000000000000..b586cb3ff0f8 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/NameAvailabilityStatus.cs @@ -0,0 +1,95 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The result of a request to check the availability of a resource name. + public partial class NameAvailabilityStatus : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatusInternal + { + + /// Backing field for property. + private string _message; + + /// + /// If any, the error message that provides more detail for the reason that the name is not available. + /// + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatusInternal.Message { get => this._message; set { {_message = value;} } } + + /// Internal Acessors for NameAvailable + bool? Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatusInternal.NameAvailable { get => this._nameAvailable; set { {_nameAvailable = value;} } } + + /// Internal Acessors for Reason + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatusInternal.Reason { get => this._reason; set { {_reason = value;} } } + + /// Backing field for property. + private bool? _nameAvailable; + + /// The value indicating whether the resource name is available. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public bool? NameAvailable { get => this._nameAvailable; } + + /// Backing field for property. + private string _reason; + + /// If any, the reason that the name is not available. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Reason { get => this._reason; } + + /// Creates an new instance. + public NameAvailabilityStatus() + { + + } + } + /// The result of a request to check the availability of a resource name. + public partial interface INameAvailabilityStatus : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable + { + /// + /// If any, the error message that provides more detail for the reason that the name is not available. + /// + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"If any, the error message that provides more detail for the reason that the name is not available.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + /// The value indicating whether the resource name is available. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The value indicating whether the resource name is available.", + SerializedName = @"nameAvailable", + PossibleTypes = new [] { typeof(bool) })] + bool? NameAvailable { get; } + /// If any, the reason that the name is not available. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"If any, the reason that the name is not available.", + SerializedName = @"reason", + PossibleTypes = new [] { typeof(string) })] + string Reason { get; } + + } + /// The result of a request to check the availability of a resource name. + internal partial interface INameAvailabilityStatusInternal + + { + /// + /// If any, the error message that provides more detail for the reason that the name is not available. + /// + string Message { get; set; } + /// The value indicating whether the resource name is available. + bool? NameAvailable { get; set; } + /// If any, the reason that the name is not available. + string Reason { get; set; } + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/NameAvailabilityStatus.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/NameAvailabilityStatus.json.cs new file mode 100644 index 000000000000..396779ae128a --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/NameAvailabilityStatus.json.cs @@ -0,0 +1,114 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The result of a request to check the availability of a resource name. + public partial class NameAvailabilityStatus + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new NameAvailabilityStatus(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal NameAvailabilityStatus(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_message = If( json?.PropertyT("message"), out var __jsonMessage) ? (string)__jsonMessage : (string)Message;} + {_nameAvailable = If( json?.PropertyT("nameAvailable"), out var __jsonNameAvailable) ? (bool?)__jsonNameAvailable : NameAvailable;} + {_reason = If( json?.PropertyT("reason"), out var __jsonReason) ? (string)__jsonReason : (string)Reason;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._nameAvailable ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonBoolean((bool)this._nameAvailable) : null, "nameAvailable" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._reason)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._reason.ToString()) : null, "reason" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinition.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinition.PowerShell.cs new file mode 100644 index 000000000000..ad76fae0e5a6 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinition.PowerShell.cs @@ -0,0 +1,143 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// The definition of a configuration store operation. + [System.ComponentModel.TypeConverter(typeof(OperationDefinitionTypeConverter))] + public partial class OperationDefinition + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationDefinition(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationDefinition(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationDefinition(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.OperationDefinitionDisplayTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).DisplayDescription, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).DisplayOperation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).DisplayProvider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).DisplayResource, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationDefinition(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.OperationDefinitionDisplayTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).DisplayDescription, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).DisplayOperation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).DisplayProvider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal)this).DisplayResource, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The definition of a configuration store operation. + [System.ComponentModel.TypeConverter(typeof(OperationDefinitionTypeConverter))] + public partial interface IOperationDefinition + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinition.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinition.TypeConverter.cs new file mode 100644 index 000000000000..1402aaeb8c87 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinition.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationDefinitionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationDefinition.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationDefinition.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationDefinition.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinition.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinition.cs new file mode 100644 index 000000000000..d40b594d63d1 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinition.cs @@ -0,0 +1,117 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The definition of a configuration store operation. + public partial class OperationDefinition : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplay _display; + + /// The display information for the configuration store operation. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplay Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.OperationDefinitionDisplay()); set => this._display = value; } + + /// The description for the operation. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Inlined)] + public string DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)Display).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)Display).Description = value; } + + /// The operation that users can perform. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Inlined)] + public string DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)Display).Operation; set => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)Display).Operation = value; } + + /// The resource provider name: Microsoft App Configuration." + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Inlined)] + public string DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)Display).Provider; } + + /// The resource on which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Inlined)] + public string DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)Display).Resource; set => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)Display).Resource = value; } + + /// Internal Acessors for Display + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplay Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal.Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.OperationDefinitionDisplay()); set { {_display = value;} } } + + /// Internal Acessors for DisplayProvider + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionInternal.DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)Display).Provider; set => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)Display).Provider = value; } + + /// Backing field for property. + private string _name; + + /// Operation name: {provider}/{resource}/{operation}. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Creates an new instance. + public OperationDefinition() + { + + } + } + /// The definition of a configuration store operation. + public partial interface IOperationDefinition : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable + { + /// The description for the operation. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The description for the operation.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string DisplayDescription { get; set; } + /// The operation that users can perform. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The operation that users can perform.", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string DisplayOperation { get; set; } + /// The resource provider name: Microsoft App Configuration." + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The resource provider name: Microsoft App Configuration.""", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string DisplayProvider { get; } + /// The resource on which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The resource on which the operation is performed.", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string DisplayResource { get; set; } + /// Operation name: {provider}/{resource}/{operation}. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Operation name: {provider}/{resource}/{operation}.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + + } + /// The definition of a configuration store operation. + internal partial interface IOperationDefinitionInternal + + { + /// The display information for the configuration store operation. + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplay Display { get; set; } + /// The description for the operation. + string DisplayDescription { get; set; } + /// The operation that users can perform. + string DisplayOperation { get; set; } + /// The resource provider name: Microsoft App Configuration." + string DisplayProvider { get; set; } + /// The resource on which the operation is performed. + string DisplayResource { get; set; } + /// Operation name: {provider}/{resource}/{operation}. + string Name { get; set; } + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinition.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinition.json.cs new file mode 100644 index 000000000000..3504f2244f54 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinition.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The definition of a configuration store operation. + public partial class OperationDefinition + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new OperationDefinition(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal OperationDefinition(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_display = If( json?.PropertyT("display"), out var __jsonDisplay) ? Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.OperationDefinitionDisplay.FromJson(__jsonDisplay) : Display;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._display ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) this._display.ToJson(null,serializationMode) : null, "display" ,container.Add ); + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionDisplay.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionDisplay.PowerShell.cs new file mode 100644 index 000000000000..8dc2d3913d19 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionDisplay.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// The display information for a configuration store operation. + [System.ComponentModel.TypeConverter(typeof(OperationDefinitionDisplayTypeConverter))] + public partial class OperationDefinitionDisplay + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplay DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationDefinitionDisplay(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplay DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationDefinitionDisplay(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplay FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationDefinitionDisplay(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)this).Description, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)this).Operation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)this).Provider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)this).Resource, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationDefinitionDisplay(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)this).Description, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)this).Operation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)this).Provider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal)this).Resource, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The display information for a configuration store operation. + [System.ComponentModel.TypeConverter(typeof(OperationDefinitionDisplayTypeConverter))] + public partial interface IOperationDefinitionDisplay + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionDisplay.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionDisplay.TypeConverter.cs new file mode 100644 index 000000000000..e91929ce083a --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionDisplay.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationDefinitionDisplayTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplay ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplay).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationDefinitionDisplay.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationDefinitionDisplay.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationDefinitionDisplay.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionDisplay.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionDisplay.cs new file mode 100644 index 000000000000..81068cbcccbe --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionDisplay.cs @@ -0,0 +1,100 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The display information for a configuration store operation. + public partial class OperationDefinitionDisplay : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplay, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal + { + + /// Backing field for property. + private string _description; + + /// The description for the operation. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Description { get => this._description; set => this._description = value; } + + /// Internal Acessors for Provider + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplayInternal.Provider { get => this._provider; set { {_provider = value;} } } + + /// Backing field for property. + private string _operation; + + /// The operation that users can perform. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Operation { get => this._operation; set => this._operation = value; } + + /// Backing field for property. + private string _provider; + + /// The resource provider name: Microsoft App Configuration." + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Provider { get => this._provider; } + + /// Backing field for property. + private string _resource; + + /// The resource on which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Resource { get => this._resource; set => this._resource = value; } + + /// Creates an new instance. + public OperationDefinitionDisplay() + { + + } + } + /// The display information for a configuration store operation. + public partial interface IOperationDefinitionDisplay : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable + { + /// The description for the operation. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The description for the operation.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; set; } + /// The operation that users can perform. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The operation that users can perform.", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string Operation { get; set; } + /// The resource provider name: Microsoft App Configuration." + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The resource provider name: Microsoft App Configuration.""", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string Provider { get; } + /// The resource on which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The resource on which the operation is performed.", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string Resource { get; set; } + + } + /// The display information for a configuration store operation. + internal partial interface IOperationDefinitionDisplayInternal + + { + /// The description for the operation. + string Description { get; set; } + /// The operation that users can perform. + string Operation { get; set; } + /// The resource provider name: Microsoft App Configuration." + string Provider { get; set; } + /// The resource on which the operation is performed. + string Resource { get; set; } + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionDisplay.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionDisplay.json.cs new file mode 100644 index 000000000000..9c37ffd335ea --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionDisplay.json.cs @@ -0,0 +1,110 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The display information for a configuration store operation. + public partial class OperationDefinitionDisplay + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplay. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplay. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionDisplay FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new OperationDefinitionDisplay(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal OperationDefinitionDisplay(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)Description;} + {_operation = If( json?.PropertyT("operation"), out var __jsonOperation) ? (string)__jsonOperation : (string)Operation;} + {_provider = If( json?.PropertyT("provider"), out var __jsonProvider) ? (string)__jsonProvider : (string)Provider;} + {_resource = If( json?.PropertyT("resource"), out var __jsonResource) ? (string)__jsonResource : (string)Resource;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + AddIf( null != (((object)this._operation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._operation.ToString()) : null, "operation" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._provider)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._provider.ToString()) : null, "provider" ,container.Add ); + } + AddIf( null != (((object)this._resource)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._resource.ToString()) : null, "resource" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionListResult.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionListResult.PowerShell.cs new file mode 100644 index 000000000000..4743bcca3b23 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionListResult.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// The result of a request to list configuration store operations. + [System.ComponentModel.TypeConverter(typeof(OperationDefinitionListResultTypeConverter))] + public partial class OperationDefinitionListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationDefinitionListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationDefinitionListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationDefinitionListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.OperationDefinitionTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationDefinitionListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.OperationDefinitionTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The result of a request to list configuration store operations. + [System.ComponentModel.TypeConverter(typeof(OperationDefinitionListResultTypeConverter))] + public partial interface IOperationDefinitionListResult + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionListResult.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionListResult.TypeConverter.cs new file mode 100644 index 000000000000..a3aad6d72736 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionListResult.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationDefinitionListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationDefinitionListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationDefinitionListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationDefinitionListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionListResult.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionListResult.cs new file mode 100644 index 000000000000..9ce1a73b5770 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionListResult.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The result of a request to list configuration store operations. + public partial class OperationDefinitionListResult : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResult, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The URI that can be used to request the next set of paged results. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition[] _value; + + /// The collection value. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public OperationDefinitionListResult() + { + + } + } + /// The result of a request to list configuration store operations. + public partial interface IOperationDefinitionListResult : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable + { + /// The URI that can be used to request the next set of paged results. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The URI that can be used to request the next set of paged results.", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The collection value. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The collection value.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition) })] + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition[] Value { get; set; } + + } + /// The result of a request to list configuration store operations. + internal partial interface IOperationDefinitionListResultInternal + + { + /// The URI that can be used to request the next set of paged results. + string NextLink { get; set; } + /// The collection value. + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionListResult.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionListResult.json.cs new file mode 100644 index 000000000000..b4d511362483 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/OperationDefinitionListResult.json.cs @@ -0,0 +1,111 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The result of a request to list configuration store operations. + public partial class OperationDefinitionListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinitionListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new OperationDefinitionListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal OperationDefinitionListResult(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition) (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.OperationDefinition.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/RegenerateKeyParameters.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/RegenerateKeyParameters.PowerShell.cs new file mode 100644 index 000000000000..a86ebdbafe60 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/RegenerateKeyParameters.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// The parameters used to regenerate an API key. + [System.ComponentModel.TypeConverter(typeof(RegenerateKeyParametersTypeConverter))] + public partial class RegenerateKeyParameters + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new RegenerateKeyParameters(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new RegenerateKeyParameters(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal RegenerateKeyParameters(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParametersInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParametersInternal)this).Id, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal RegenerateKeyParameters(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParametersInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParametersInternal)this).Id, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The parameters used to regenerate an API key. + [System.ComponentModel.TypeConverter(typeof(RegenerateKeyParametersTypeConverter))] + public partial interface IRegenerateKeyParameters + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/RegenerateKeyParameters.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/RegenerateKeyParameters.TypeConverter.cs new file mode 100644 index 000000000000..4a18c323348a --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/RegenerateKeyParameters.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class RegenerateKeyParametersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return RegenerateKeyParameters.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return RegenerateKeyParameters.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return RegenerateKeyParameters.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/RegenerateKeyParameters.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/RegenerateKeyParameters.cs new file mode 100644 index 000000000000..f3956e0ec543 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/RegenerateKeyParameters.cs @@ -0,0 +1,46 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The parameters used to regenerate an API key. + public partial class RegenerateKeyParameters : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParametersInternal + { + + /// Backing field for property. + private string _id; + + /// The id of the key to regenerate. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Creates an new instance. + public RegenerateKeyParameters() + { + + } + } + /// The parameters used to regenerate an API key. + public partial interface IRegenerateKeyParameters : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable + { + /// The id of the key to regenerate. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The id of the key to regenerate.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + + } + /// The parameters used to regenerate an API key. + internal partial interface IRegenerateKeyParametersInternal + + { + /// The id of the key to regenerate. + string Id { get; set; } + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/RegenerateKeyParameters.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/RegenerateKeyParameters.json.cs new file mode 100644 index 000000000000..1be3f2360689 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/RegenerateKeyParameters.json.cs @@ -0,0 +1,101 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The parameters used to regenerate an API key. + public partial class RegenerateKeyParameters + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new RegenerateKeyParameters(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal RegenerateKeyParameters(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/Resource.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/Resource.PowerShell.cs new file mode 100644 index 000000000000..128039a438e8 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/Resource.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// An Azure resource. + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial class Resource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResource DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Resource(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResource DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Resource(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Resource(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ResourceTagsTypeConverter.ConvertFrom); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Resource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ResourceTagsTypeConverter.ConvertFrom); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// An Azure resource. + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial interface IResource + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/Resource.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/Resource.TypeConverter.cs new file mode 100644 index 000000000000..80235298bb49 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/Resource.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResource).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Resource.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Resource.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Resource.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/Resource.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/Resource.cs new file mode 100644 index 000000000000..55aa9a801526 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/Resource.cs @@ -0,0 +1,129 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// An Azure resource. + public partial class Resource : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResource, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal + { + + /// Backing field for property. + private string _id; + + /// The resource ID. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Backing field for property. + private string _location; + + /// + /// The location of the resource. This cannot be changed after the resource is created. + /// + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// The name of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags _tag; + + /// The tags of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ResourceTags()); set => this._tag = value; } + + /// Backing field for property. + private string _type; + + /// The type of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public Resource() + { + + } + } + /// An Azure resource. + public partial interface IResource : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable + { + /// The resource ID. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The resource ID.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// + /// The location of the resource. This cannot be changed after the resource is created. + /// + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The location of the resource. This cannot be changed after the resource is created.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + /// The name of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The name of the resource.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// The tags of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The tags of the resource.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags) })] + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags Tag { get; set; } + /// The type of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The type of the resource.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// An Azure resource. + internal partial interface IResourceInternal + + { + /// The resource ID. + string Id { get; set; } + /// + /// The location of the resource. This cannot be changed after the resource is created. + /// + string Location { get; set; } + /// The name of the resource. + string Name { get; set; } + /// The tags of the resource. + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags Tag { get; set; } + /// The type of the resource. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/Resource.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/Resource.json.cs new file mode 100644 index 000000000000..b3894d637e79 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/Resource.json.cs @@ -0,0 +1,118 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// An Azure resource. + public partial class Resource + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new Resource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal Resource(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)Type;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)Location;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ResourceTags.FromJson(__jsonTags) : Tag;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ResourceTags.PowerShell.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ResourceTags.PowerShell.cs new file mode 100644 index 000000000000..deca915da250 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ResourceTags.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// The tags of the resource. + [System.ComponentModel.TypeConverter(typeof(ResourceTagsTypeConverter))] + public partial class ResourceTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ResourceTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ResourceTags(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ResourceTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ResourceTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The tags of the resource. + [System.ComponentModel.TypeConverter(typeof(ResourceTagsTypeConverter))] + public partial interface IResourceTags + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ResourceTags.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ResourceTags.TypeConverter.cs new file mode 100644 index 000000000000..243a1bd41aa5 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ResourceTags.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ResourceTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ResourceTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ResourceTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ResourceTags.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ResourceTags.cs new file mode 100644 index 000000000000..b52cd8f0dc00 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ResourceTags.cs @@ -0,0 +1,30 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The tags of the resource. + public partial class ResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTagsInternal + { + + /// Creates an new instance. + public ResourceTags() + { + + } + } + /// The tags of the resource. + public partial interface IResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray + { + + } + /// The tags of the resource. + internal partial interface IResourceTagsInternal + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ResourceTags.dictionary.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ResourceTags.dictionary.cs new file mode 100644 index 000000000000..77d9e48697fa --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ResourceTags.dictionary.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + public partial class ResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); + + public void Clear() => __additionalProperties.Clear(); + + /// + public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); + + /// + public void CopyFrom(global::System.Collections.IDictionary source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public void CopyFrom(global::System.Management.Automation.PSObject source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public bool Remove(global::System.String key) => __additionalProperties.Remove( key); + + /// + /// + public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ResourceTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/Api20190201Preview/ResourceTags.json.cs b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ResourceTags.json.cs new file mode 100644 index 000000000000..07dba3b7b03c --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/Api20190201Preview/ResourceTags.json.cs @@ -0,0 +1,102 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// The tags of the resource. + public partial class ResourceTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new ResourceTags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + /// + internal ResourceTags(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet exclusions = null) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/AppConfigurationIdentity.PowerShell.cs b/src/AppConfiguration/generated/api/Models/AppConfigurationIdentity.PowerShell.cs new file mode 100644 index 000000000000..47a34ea6db8b --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/AppConfigurationIdentity.PowerShell.cs @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(AppConfigurationIdentityTypeConverter))] + public partial class AppConfigurationIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal AppConfigurationIdentity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentityInternal)this).ConfigStoreName = (string) content.GetValueForProperty("ConfigStoreName",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentityInternal)this).ConfigStoreName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentityInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal AppConfigurationIdentity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentityInternal)this).ConfigStoreName = (string) content.GetValueForProperty("ConfigStoreName",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentityInternal)this).ConfigStoreName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentityInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AppConfigurationIdentity(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AppConfigurationIdentity(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + [System.ComponentModel.TypeConverter(typeof(AppConfigurationIdentityTypeConverter))] + public partial interface IAppConfigurationIdentity + + { + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/AppConfigurationIdentity.TypeConverter.cs b/src/AppConfiguration/generated/api/Models/AppConfigurationIdentity.TypeConverter.cs new file mode 100644 index 000000000000..bffb6b471428 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/AppConfigurationIdentity.TypeConverter.cs @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AppConfigurationIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + // we allow string conversion too. + if (type == typeof(global::System.String)) + { + return true; + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + // support direct string to id type conversion. + if (type == typeof(global::System.String)) + { + return new AppConfigurationIdentity { Id = sourceValue }; + } + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AppConfigurationIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AppConfigurationIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AppConfigurationIdentity.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/AppConfigurationIdentity.cs b/src/AppConfiguration/generated/api/Models/AppConfigurationIdentity.cs new file mode 100644 index 000000000000..28fdc825ed3d --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/AppConfigurationIdentity.cs @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + public partial class AppConfigurationIdentity : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentityInternal + { + + /// Backing field for property. + private string _configStoreName; + + /// The name of the configuration store. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string ConfigStoreName { get => this._configStoreName; set => this._configStoreName = value; } + + /// Backing field for property. + private string _id; + + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group to which the container registry belongs. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The Microsoft Azure subscription ID. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Creates an new instance. + public AppConfigurationIdentity() + { + + } + } + public partial interface IAppConfigurationIdentity : + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable + { + /// The name of the configuration store. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The name of the configuration store.", + SerializedName = @"configStoreName", + PossibleTypes = new [] { typeof(string) })] + string ConfigStoreName { get; set; } + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource identity path", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// The name of the resource group to which the container registry belongs. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The name of the resource group to which the container registry belongs.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + string ResourceGroupName { get; set; } + /// The Microsoft Azure subscription ID. + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The Microsoft Azure subscription ID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string SubscriptionId { get; set; } + + } + internal partial interface IAppConfigurationIdentityInternal + + { + /// The name of the configuration store. + string ConfigStoreName { get; set; } + /// Resource identity path + string Id { get; set; } + /// The name of the resource group to which the container registry belongs. + string ResourceGroupName { get; set; } + /// The Microsoft Azure subscription ID. + string SubscriptionId { get; set; } + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Models/AppConfigurationIdentity.json.cs b/src/AppConfiguration/generated/api/Models/AppConfigurationIdentity.json.cs new file mode 100644 index 000000000000..923e67e62168 --- /dev/null +++ b/src/AppConfiguration/generated/api/Models/AppConfigurationIdentity.json.cs @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + public partial class AppConfigurationIdentity + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container); + + /// + /// BeforeFromJson will be called before the json deserialization has commenced, allowing complete customization of + /// the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JsonNode that should be deserialized into this object. + /// Determines if the rest of the deserialization should be processed, or if the method should return + /// instantly. + + partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json, ref bool returnNow); + + /// + /// BeforeToJson will be called before the json serialization has commenced, allowing complete customization of the + /// object before it is serialized. + /// If you wish to disable the default serialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The JSON container that the serialization result will be placed in. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal AppConfigurationIdentity(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_configStoreName = If( json?.PropertyT("configStoreName"), out var __jsonConfigStoreName) ? (string)__jsonConfigStoreName : (string)ConfigStoreName;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + {_resourceGroupName = If( json?.PropertyT("resourceGroupName"), out var __jsonResourceGroupName) ? (string)__jsonResourceGroupName : (string)ResourceGroupName;} + {_subscriptionId = If( json?.PropertyT("subscriptionId"), out var __jsonSubscriptionId) ? (string)__jsonSubscriptionId : (string)SubscriptionId;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new AppConfigurationIdentity(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._configStoreName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._configStoreName.ToString()) : null, "configStoreName" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + AddIf( null != (((object)this._resourceGroupName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._resourceGroupName.ToString()) : null, "resourceGroupName" ,container.Add ); + AddIf( null != (((object)this._subscriptionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Support/ProvisioningState.Completer.cs b/src/AppConfiguration/generated/api/Support/ProvisioningState.Completer.cs new file mode 100644 index 000000000000..d83e3be2cd8e --- /dev/null +++ b/src/AppConfiguration/generated/api/Support/ProvisioningState.Completer.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support +{ + + /// Argument completer implementation for ProvisioningState. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningStateTypeConverter))] + public partial struct ProvisioningState : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Creating".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Creating", "Creating", global::System.Management.Automation.CompletionResultType.ParameterValue, "Creating"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Updating".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Updating", "Updating", global::System.Management.Automation.CompletionResultType.ParameterValue, "Updating"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Deleting".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Deleting", "Deleting", global::System.Management.Automation.CompletionResultType.ParameterValue, "Deleting"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Succeeded".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Succeeded", "Succeeded", global::System.Management.Automation.CompletionResultType.ParameterValue, "Succeeded"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Failed".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Failed", "Failed", global::System.Management.Automation.CompletionResultType.ParameterValue, "Failed"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Canceled".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Canceled", "Canceled", global::System.Management.Automation.CompletionResultType.ParameterValue, "Canceled"); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Support/ProvisioningState.TypeConverter.cs b/src/AppConfiguration/generated/api/Support/ProvisioningState.TypeConverter.cs new file mode 100644 index 000000000000..e727f0bbf820 --- /dev/null +++ b/src/AppConfiguration/generated/api/Support/ProvisioningState.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support +{ + + /// TypeConverter implementation for ProvisioningState. + public partial class ProvisioningStateTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ProvisioningState.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/api/Support/ProvisioningState.cs b/src/AppConfiguration/generated/api/Support/ProvisioningState.cs new file mode 100644 index 000000000000..ed353e7f1997 --- /dev/null +++ b/src/AppConfiguration/generated/api/Support/ProvisioningState.cs @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support +{ + + public partial struct ProvisioningState : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState Canceled = @"Canceled"; + + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState Creating = @"Creating"; + + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState Deleting = @"Deleting"; + + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState Failed = @"Failed"; + + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState Succeeded = @"Succeeded"; + + public static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState Updating = @"Updating"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Conversion from arbitrary object to ProvisioningState + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new ProvisioningState(System.Convert.ToString(value)); + } + + /// Compares values of enum type ProvisioningState + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type ProvisioningState (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is ProvisioningState && Equals((ProvisioningState)obj); + } + + /// Returns hashCode for enum ProvisioningState + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Creates an instance of the + /// the value to create an instance for. + private ProvisioningState(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Returns string representation for ProvisioningState + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to ProvisioningState + /// the value to convert to an instance of . + + public static implicit operator ProvisioningState(string value) + { + return new ProvisioningState(value); + } + + /// Implicit operator to convert ProvisioningState to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState e) + { + return e._value; + } + + /// Overriding != operator for enum ProvisioningState + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState e1, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum ProvisioningState + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState e1, Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support.ProvisioningState e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationOperation_List.cs b/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationOperation_List.cs new file mode 100644 index 000000000000..2da2638cb26f --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationOperation_List.cs @@ -0,0 +1,379 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Lists the operations available from this provider. + /// + /// [OpenAPI] Operations_List=>GET:"/providers/Microsoft.AppConfiguration/operations" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzAppConfigurationOperation_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Lists the operations available from this provider.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class GetAzAppConfigurationOperation_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _skipToken; + + /// + /// A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response + /// contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting + /// point to use for subsequent calls. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls.", + SerializedName = @"$skipToken", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Query)] + public string SkipToken { get => this._skipToken; set => this._skipToken = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzAppConfigurationOperation_List() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsList(this.InvocationInformation.BoundParameters.ContainsKey("SkipToken") ? SkipToken : null, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SkipToken=this.InvocationInformation.BoundParameters.ContainsKey("SkipToken") ? SkipToken : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SkipToken=this.InvocationInformation.BoundParameters.ContainsKey("SkipToken") ? SkipToken : null }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SkipToken=this.InvocationInformation.BoundParameters.ContainsKey("SkipToken") ? SkipToken : null }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + var result = await response; + WriteObject(result.Value,true); + if (result.NextLink != null) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationStoreKey_List.cs b/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationStoreKey_List.cs new file mode 100644 index 000000000000..664a2fb72245 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationStoreKey_List.cs @@ -0,0 +1,430 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Lists the access key for the specified configuration store. + /// + /// [OpenAPI] ConfigurationStores_ListKeys=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}/ListKeys" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzAppConfigurationStoreKey_List", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Lists the access key for the specified configuration store.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class GetAzAppConfigurationStoreKey_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the configuration store. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the configuration store.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the configuration store.", + SerializedName = @"configStoreName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group to which the container registry belongs. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group to which the container registry belongs.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group to which the container registry belongs.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _skipToken; + + /// + /// A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response + /// contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting + /// point to use for subsequent calls. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls.", + SerializedName = @"$skipToken", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Query)] + public string SkipToken { get => this._skipToken; set => this._skipToken = value; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// The Microsoft Azure subscription ID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Microsoft Azure subscription ID.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Microsoft Azure subscription ID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzAppConfigurationStoreKey_List() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConfigurationStoresListKeys' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConfigurationStoresListKeys(SubscriptionId, ResourceGroupName, Name, this.InvocationInformation.BoundParameters.ContainsKey("SkipToken") ? SkipToken : null, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name,SkipToken=this.InvocationInformation.BoundParameters.ContainsKey("SkipToken") ? SkipToken : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, SkipToken=this.InvocationInformation.BoundParameters.ContainsKey("SkipToken") ? SkipToken : null }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, SkipToken=this.InvocationInformation.BoundParameters.ContainsKey("SkipToken") ? SkipToken : null }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + var result = await response; + WriteObject(result.Value,true); + if (result.NextLink != null) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConfigurationStoresListKeys_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationStore_Get.cs b/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationStore_Get.cs new file mode 100644 index 000000000000..acea8659229e --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationStore_Get.cs @@ -0,0 +1,398 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Gets the properties of the specified configuration store. + /// + /// [OpenAPI] ConfigurationStores_Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzAppConfigurationStore_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Gets the properties of the specified configuration store.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class GetAzAppConfigurationStore_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the configuration store. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the configuration store.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the configuration store.", + SerializedName = @"configStoreName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group to which the container registry belongs. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group to which the container registry belongs.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group to which the container registry belongs.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// The Microsoft Azure subscription ID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Microsoft Azure subscription ID.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Microsoft Azure subscription ID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzAppConfigurationStore_Get() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConfigurationStoresGet(SubscriptionId, ResourceGroupName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationStore_GetViaIdentity.cs b/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationStore_GetViaIdentity.cs new file mode 100644 index 000000000000..a271f59f03a5 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationStore_GetViaIdentity.cs @@ -0,0 +1,377 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Gets the properties of the specified configuration store. + /// + /// [OpenAPI] ConfigurationStores_Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzAppConfigurationStore_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Gets the properties of the specified configuration store.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class GetAzAppConfigurationStore_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzAppConfigurationStore_GetViaIdentity() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ConfigurationStoresGetViaIdentity(InputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ConfigStoreName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ConfigStoreName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ConfigurationStoresGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ConfigStoreName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationStore_List.cs b/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationStore_List.cs new file mode 100644 index 000000000000..7fdcd26fbbea --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationStore_List.cs @@ -0,0 +1,399 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Lists the configuration stores for a given subscription. + /// + /// [OpenAPI] ConfigurationStores_List=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.AppConfiguration/configurationStores" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzAppConfigurationStore_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Lists the configuration stores for a given subscription.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class GetAzAppConfigurationStore_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _skipToken; + + /// + /// A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response + /// contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting + /// point to use for subsequent calls. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls.", + SerializedName = @"$skipToken", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Query)] + public string SkipToken { get => this._skipToken; set => this._skipToken = value; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// The Microsoft Azure subscription ID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Microsoft Azure subscription ID.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Microsoft Azure subscription ID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzAppConfigurationStore_List() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConfigurationStoresList(SubscriptionId, this.InvocationInformation.BoundParameters.ContainsKey("SkipToken") ? SkipToken : null, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,SkipToken=this.InvocationInformation.BoundParameters.ContainsKey("SkipToken") ? SkipToken : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, SkipToken=this.InvocationInformation.BoundParameters.ContainsKey("SkipToken") ? SkipToken : null }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, SkipToken=this.InvocationInformation.BoundParameters.ContainsKey("SkipToken") ? SkipToken : null }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + var result = await response; + WriteObject(result.Value,true); + if (result.NextLink != null) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConfigurationStoresList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationStore_List1.cs b/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationStore_List1.cs new file mode 100644 index 000000000000..1586b8b92af6 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/GetAzAppConfigurationStore_List1.cs @@ -0,0 +1,413 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Lists the configuration stores for a given resource group. + /// + /// [OpenAPI] ConfigurationStores_ListByResourceGroup=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzAppConfigurationStore_List1")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Lists the configuration stores for a given resource group.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class GetAzAppConfigurationStore_List1 : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group to which the container registry belongs. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group to which the container registry belongs.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group to which the container registry belongs.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _skipToken; + + /// + /// A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response + /// contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting + /// point to use for subsequent calls. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls.", + SerializedName = @"$skipToken", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Query)] + public string SkipToken { get => this._skipToken; set => this._skipToken = value; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// The Microsoft Azure subscription ID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Microsoft Azure subscription ID.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Microsoft Azure subscription ID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzAppConfigurationStore_List1() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConfigurationStoresListByResourceGroup(SubscriptionId, ResourceGroupName, this.InvocationInformation.BoundParameters.ContainsKey("SkipToken") ? SkipToken : null, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,SkipToken=this.InvocationInformation.BoundParameters.ContainsKey("SkipToken") ? SkipToken : null}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, SkipToken=this.InvocationInformation.BoundParameters.ContainsKey("SkipToken") ? SkipToken : null }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, SkipToken=this.InvocationInformation.BoundParameters.ContainsKey("SkipToken") ? SkipToken : null }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + var result = await response; + WriteObject(result.Value,true); + if (result.NextLink != null) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConfigurationStoresListByResourceGroup_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStoreKey_Regenerate.cs b/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStoreKey_Regenerate.cs new file mode 100644 index 000000000000..db223b4b9595 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStoreKey_Regenerate.cs @@ -0,0 +1,412 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Regenerates an access key for the specified configuration store. + /// + /// [OpenAPI] ConfigurationStores_RegenerateKey=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}/RegenerateKey" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzAppConfigurationStoreKey_Regenerate", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Regenerates an access key for the specified configuration store.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class NewAzAppConfigurationStoreKey_Regenerate : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the configuration store. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the configuration store.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the configuration store.", + SerializedName = @"configStoreName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters _regenerateKeyParameter; + + /// The parameters used to regenerate an API key. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parameters used to regenerate an API key.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parameters used to regenerate an API key.", + SerializedName = @"regenerateKeyParameters", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters) })] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters RegenerateKeyParameter { get => this._regenerateKeyParameter; set => this._regenerateKeyParameter = value; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group to which the container registry belongs. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group to which the container registry belongs.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group to which the container registry belongs.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The Microsoft Azure subscription ID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Microsoft Azure subscription ID.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Microsoft Azure subscription ID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public NewAzAppConfigurationStoreKey_Regenerate() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConfigurationStoresRegenerateKey' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConfigurationStoresRegenerateKey(SubscriptionId, ResourceGroupName, Name, RegenerateKeyParameter, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name,body=RegenerateKeyParameter}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=RegenerateKeyParameter }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=RegenerateKeyParameter }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStoreKey_RegenerateExpanded.cs b/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStoreKey_RegenerateExpanded.cs new file mode 100644 index 000000000000..730a810fa265 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStoreKey_RegenerateExpanded.cs @@ -0,0 +1,415 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Regenerates an access key for the specified configuration store. + /// + /// [OpenAPI] ConfigurationStores_RegenerateKey=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}/RegenerateKey" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzAppConfigurationStoreKey_RegenerateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Regenerates an access key for the specified configuration store.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class NewAzAppConfigurationStoreKey_RegenerateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// The id of the key to regenerate. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The id of the key to regenerate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The id of the key to regenerate.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + public string Id { get => RegenerateKeyParametersBody.Id ?? null; set => RegenerateKeyParametersBody.Id = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the configuration store. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the configuration store.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the configuration store.", + SerializedName = @"configStoreName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters _regenerateKeyParametersBody= new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.RegenerateKeyParameters(); + + /// The parameters used to regenerate an API key. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters RegenerateKeyParametersBody { get => this._regenerateKeyParametersBody; set => this._regenerateKeyParametersBody = value; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group to which the container registry belongs. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group to which the container registry belongs.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group to which the container registry belongs.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The Microsoft Azure subscription ID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Microsoft Azure subscription ID.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Microsoft Azure subscription ID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public NewAzAppConfigurationStoreKey_RegenerateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConfigurationStoresRegenerateKey' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConfigurationStoresRegenerateKey(SubscriptionId, ResourceGroupName, Name, RegenerateKeyParametersBody, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name,body=RegenerateKeyParametersBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=RegenerateKeyParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=RegenerateKeyParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStoreKey_RegenerateViaIdentity.cs b/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStoreKey_RegenerateViaIdentity.cs new file mode 100644 index 000000000000..223a29d90a66 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStoreKey_RegenerateViaIdentity.cs @@ -0,0 +1,394 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Regenerates an access key for the specified configuration store. + /// + /// [OpenAPI] ConfigurationStores_RegenerateKey=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}/RegenerateKey" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzAppConfigurationStoreKey_RegenerateViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Regenerates an access key for the specified configuration store.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class NewAzAppConfigurationStoreKey_RegenerateViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters _regenerateKeyParameter; + + /// The parameters used to regenerate an API key. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parameters used to regenerate an API key.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parameters used to regenerate an API key.", + SerializedName = @"regenerateKeyParameters", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters) })] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters RegenerateKeyParameter { get => this._regenerateKeyParameter; set => this._regenerateKeyParameter = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public NewAzAppConfigurationStoreKey_RegenerateViaIdentity() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConfigurationStoresRegenerateKey' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ConfigurationStoresRegenerateKeyViaIdentity(InputObject.Id, RegenerateKeyParameter, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ConfigStoreName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ConfigStoreName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ConfigurationStoresRegenerateKey(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ConfigStoreName ?? null, RegenerateKeyParameter, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=RegenerateKeyParameter}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=RegenerateKeyParameter }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=RegenerateKeyParameter }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStoreKey_RegenerateViaIdentityExpanded.cs b/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStoreKey_RegenerateViaIdentityExpanded.cs new file mode 100644 index 000000000000..743f202d3bca --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStoreKey_RegenerateViaIdentityExpanded.cs @@ -0,0 +1,397 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Regenerates an access key for the specified configuration store. + /// + /// [OpenAPI] ConfigurationStores_RegenerateKey=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}/RegenerateKey" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzAppConfigurationStoreKey_RegenerateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Regenerates an access key for the specified configuration store.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class NewAzAppConfigurationStoreKey_RegenerateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// The id of the key to regenerate. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The id of the key to regenerate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The id of the key to regenerate.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + public string Id { get => RegenerateKeyParametersBody.Id ?? null; set => RegenerateKeyParametersBody.Id = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters _regenerateKeyParametersBody= new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.RegenerateKeyParameters(); + + /// The parameters used to regenerate an API key. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters RegenerateKeyParametersBody { get => this._regenerateKeyParametersBody; set => this._regenerateKeyParametersBody = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public NewAzAppConfigurationStoreKey_RegenerateViaIdentityExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConfigurationStoresRegenerateKey' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ConfigurationStoresRegenerateKeyViaIdentity(InputObject.Id, RegenerateKeyParametersBody, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ConfigStoreName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ConfigStoreName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ConfigurationStoresRegenerateKey(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ConfigStoreName ?? null, RegenerateKeyParametersBody, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=RegenerateKeyParametersBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=RegenerateKeyParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=RegenerateKeyParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStore_Create.cs b/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStore_Create.cs new file mode 100644 index 000000000000..ae93c4b20ab1 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStore_Create.cs @@ -0,0 +1,482 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Creates a configuration store with the specified parameters. + /// + /// [OpenAPI] ConfigurationStores_Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzAppConfigurationStore_Create", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Creates a configuration store with the specified parameters.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class NewAzAppConfigurationStore_Create : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore _configStoreCreationParameter; + + /// + /// The configuration store along with all resource properties. The Configuration Store will have all information to begin + /// utilizing it. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The configuration store along with all resource properties. The Configuration Store will have all information to begin utilizing it.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The configuration store along with all resource properties. The Configuration Store will have all information to begin utilizing it.", + SerializedName = @"configStoreCreationParameters", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore) })] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore ConfigStoreCreationParameter { get => this._configStoreCreationParameter; set => this._configStoreCreationParameter = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the configuration store. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the configuration store.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the configuration store.", + SerializedName = @"configStoreName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group to which the container registry belongs. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group to which the container registry belongs.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group to which the container registry belongs.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The Microsoft Azure subscription ID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Microsoft Azure subscription ID.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Microsoft Azure subscription ID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzAppConfigurationStore_Create + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets.NewAzAppConfigurationStore_Create Clone() + { + var clone = new NewAzAppConfigurationStore_Create(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + clone.ConfigStoreCreationParameter = this.ConfigStoreCreationParameter; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public NewAzAppConfigurationStore_Create() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConfigurationStoresCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConfigurationStoresCreate(SubscriptionId, ResourceGroupName, Name, ConfigStoreCreationParameter, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name,body=ConfigStoreCreationParameter}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=ConfigStoreCreationParameter }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=ConfigStoreCreationParameter }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStore_CreateExpanded.cs b/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStore_CreateExpanded.cs new file mode 100644 index 000000000000..b12ba7f45314 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStore_CreateExpanded.cs @@ -0,0 +1,499 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Creates a configuration store with the specified parameters. + /// + /// [OpenAPI] ConfigurationStores_Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzAppConfigurationStore_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Creates a configuration store with the specified parameters.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class NewAzAppConfigurationStore_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore _configStoreCreationParametersBody= new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStore(); + + /// + /// The configuration store along with all resource properties. The Configuration Store will have all information to begin + /// utilizing it. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore ConfigStoreCreationParametersBody { get => this._configStoreCreationParametersBody; set => this._configStoreCreationParametersBody = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// The location of the resource. This cannot be changed after the resource is created. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The location of the resource. This cannot be changed after the resource is created.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The location of the resource. This cannot be changed after the resource is created.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => ConfigStoreCreationParametersBody.Location ?? null; set => ConfigStoreCreationParametersBody.Location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the configuration store. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the configuration store.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the configuration store.", + SerializedName = @"configStoreName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group to which the container registry belongs. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group to which the container registry belongs.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group to which the container registry belongs.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The Microsoft Azure subscription ID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Microsoft Azure subscription ID.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Microsoft Azure subscription ID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// The tags of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The tags of the resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The tags of the resource.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags Tag { get => ConfigStoreCreationParametersBody.Tag ?? null /* object */; set => ConfigStoreCreationParametersBody.Tag = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzAppConfigurationStore_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets.NewAzAppConfigurationStore_CreateExpanded Clone() + { + var clone = new NewAzAppConfigurationStore_CreateExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.ConfigStoreCreationParametersBody = this.ConfigStoreCreationParametersBody; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public NewAzAppConfigurationStore_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConfigurationStoresCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConfigurationStoresCreate(SubscriptionId, ResourceGroupName, Name, ConfigStoreCreationParametersBody, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name,body=ConfigStoreCreationParametersBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=ConfigStoreCreationParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=ConfigStoreCreationParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStore_CreateViaIdentity.cs b/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStore_CreateViaIdentity.cs new file mode 100644 index 000000000000..03ffd00f5911 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStore_CreateViaIdentity.cs @@ -0,0 +1,461 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Creates a configuration store with the specified parameters. + /// + /// [OpenAPI] ConfigurationStores_Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzAppConfigurationStore_CreateViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Creates a configuration store with the specified parameters.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class NewAzAppConfigurationStore_CreateViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore _configStoreCreationParameter; + + /// + /// The configuration store along with all resource properties. The Configuration Store will have all information to begin + /// utilizing it. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The configuration store along with all resource properties. The Configuration Store will have all information to begin utilizing it.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The configuration store along with all resource properties. The Configuration Store will have all information to begin utilizing it.", + SerializedName = @"configStoreCreationParameters", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore) })] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore ConfigStoreCreationParameter { get => this._configStoreCreationParameter; set => this._configStoreCreationParameter = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzAppConfigurationStore_CreateViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets.NewAzAppConfigurationStore_CreateViaIdentity Clone() + { + var clone = new NewAzAppConfigurationStore_CreateViaIdentity(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.ConfigStoreCreationParameter = this.ConfigStoreCreationParameter; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public NewAzAppConfigurationStore_CreateViaIdentity() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConfigurationStoresCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ConfigurationStoresCreateViaIdentity(InputObject.Id, ConfigStoreCreationParameter, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ConfigStoreName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ConfigStoreName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ConfigurationStoresCreate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ConfigStoreName ?? null, ConfigStoreCreationParameter, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ConfigStoreCreationParameter}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ConfigStoreCreationParameter }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ConfigStoreCreationParameter }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStore_CreateViaIdentityExpanded.cs b/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStore_CreateViaIdentityExpanded.cs new file mode 100644 index 000000000000..1702401505d8 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/NewAzAppConfigurationStore_CreateViaIdentityExpanded.cs @@ -0,0 +1,478 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Creates a configuration store with the specified parameters. + /// + /// [OpenAPI] ConfigurationStores_Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzAppConfigurationStore_CreateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Creates a configuration store with the specified parameters.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class NewAzAppConfigurationStore_CreateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore _configStoreCreationParametersBody= new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStore(); + + /// + /// The configuration store along with all resource properties. The Configuration Store will have all information to begin + /// utilizing it. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore ConfigStoreCreationParametersBody { get => this._configStoreCreationParametersBody; set => this._configStoreCreationParametersBody = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// The location of the resource. This cannot be changed after the resource is created. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The location of the resource. This cannot be changed after the resource is created.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The location of the resource. This cannot be changed after the resource is created.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => ConfigStoreCreationParametersBody.Location ?? null; set => ConfigStoreCreationParametersBody.Location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// The tags of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The tags of the resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The tags of the resource.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IResourceTags Tag { get => ConfigStoreCreationParametersBody.Tag ?? null /* object */; set => ConfigStoreCreationParametersBody.Tag = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzAppConfigurationStore_CreateViaIdentityExpanded + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets.NewAzAppConfigurationStore_CreateViaIdentityExpanded Clone() + { + var clone = new NewAzAppConfigurationStore_CreateViaIdentityExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.ConfigStoreCreationParametersBody = this.ConfigStoreCreationParametersBody; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public NewAzAppConfigurationStore_CreateViaIdentityExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConfigurationStoresCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ConfigurationStoresCreateViaIdentity(InputObject.Id, ConfigStoreCreationParametersBody, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ConfigStoreName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ConfigStoreName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ConfigurationStoresCreate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ConfigStoreName ?? null, ConfigStoreCreationParametersBody, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ConfigStoreCreationParametersBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ConfigStoreCreationParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ConfigStoreCreationParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/RemoveAzAppConfigurationStore_Delete.cs b/src/AppConfiguration/generated/cmdlets/RemoveAzAppConfigurationStore_Delete.cs new file mode 100644 index 000000000000..bf9f1c9ccd02 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/RemoveAzAppConfigurationStore_Delete.cs @@ -0,0 +1,503 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Deletes a configuration store. + /// + /// [OpenAPI] ConfigurationStores_Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzAppConfigurationStore_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Deletes a configuration store.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class RemoveAzAppConfigurationStore_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the configuration store. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the configuration store.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the configuration store.", + SerializedName = @"configStoreName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group to which the container registry belongs. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group to which the container registry belongs.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group to which the container registry belongs.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The Microsoft Azure subscription ID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Microsoft Azure subscription ID.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Microsoft Azure subscription ID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnNoContent will be called before the regular onNoContent has been processed, allowing customization of + /// what happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onNoContent method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnNoContent(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzAppConfigurationStore_Delete + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets.RemoveAzAppConfigurationStore_Delete Clone() + { + var clone = new RemoveAzAppConfigurationStore_Delete(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConfigurationStoresDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConfigurationStoresDelete(SubscriptionId, ResourceGroupName, Name, onOk, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzAppConfigurationStore_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 204 (NoContent). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onNoContent(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnNoContent(responseMessage, ref _returnNow); + // if overrideOnNoContent has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onNoContent - response for 204 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/RemoveAzAppConfigurationStore_DeleteViaIdentity.cs b/src/AppConfiguration/generated/cmdlets/RemoveAzAppConfigurationStore_DeleteViaIdentity.cs new file mode 100644 index 000000000000..e94f0499a923 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/RemoveAzAppConfigurationStore_DeleteViaIdentity.cs @@ -0,0 +1,482 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Deletes a configuration store. + /// + /// [OpenAPI] ConfigurationStores_Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzAppConfigurationStore_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Deletes a configuration store.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class RemoveAzAppConfigurationStore_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnNoContent will be called before the regular onNoContent has been processed, allowing customization of + /// what happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onNoContent method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnNoContent(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzAppConfigurationStore_DeleteViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets.RemoveAzAppConfigurationStore_DeleteViaIdentity Clone() + { + var clone = new RemoveAzAppConfigurationStore_DeleteViaIdentity(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConfigurationStoresDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ConfigurationStoresDeleteViaIdentity(InputObject.Id, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ConfigStoreName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ConfigStoreName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ConfigurationStoresDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ConfigStoreName ?? null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzAppConfigurationStore_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 204 (NoContent). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onNoContent(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnNoContent(responseMessage, ref _returnNow); + // if overrideOnNoContent has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onNoContent - response for 204 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/TestAzAppConfigurationStoreNameAvailability_Check.cs b/src/AppConfiguration/generated/cmdlets/TestAzAppConfigurationStoreNameAvailability_Check.cs new file mode 100644 index 000000000000..c624a8c54a95 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/TestAzAppConfigurationStoreNameAvailability_Check.cs @@ -0,0 +1,384 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Checks whether the configuration store name is available for use. + /// + /// [OpenAPI] Operations_CheckNameAvailability=>POST:"/subscriptions/{subscriptionId}/providers/Microsoft.AppConfiguration/checkNameAvailability" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzAppConfigurationStoreNameAvailability_Check", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Checks whether the configuration store name is available for use.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class TestAzAppConfigurationStoreNameAvailability_Check : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters _checkNameAvailabilityParameter; + + /// Parameters used for checking whether a resource name is available. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Parameters used for checking whether a resource name is available.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Parameters used for checking whether a resource name is available.", + SerializedName = @"checkNameAvailabilityParameters", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters) })] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters CheckNameAvailabilityParameter { get => this._checkNameAvailabilityParameter; set => this._checkNameAvailabilityParameter = value; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _subscriptionId; + + /// The Microsoft Azure subscription ID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Microsoft Azure subscription ID.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Microsoft Azure subscription ID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OperationsCheckNameAvailability' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsCheckNameAvailability(SubscriptionId, CheckNameAvailabilityParameter, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,body=CheckNameAvailabilityParameter}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public TestAzAppConfigurationStoreNameAvailability_Check() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, body=CheckNameAvailabilityParameter }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, body=CheckNameAvailabilityParameter }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/TestAzAppConfigurationStoreNameAvailability_CheckExpanded.cs b/src/AppConfiguration/generated/cmdlets/TestAzAppConfigurationStoreNameAvailability_CheckExpanded.cs new file mode 100644 index 000000000000..ce1ed3b4cdb6 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/TestAzAppConfigurationStoreNameAvailability_CheckExpanded.cs @@ -0,0 +1,387 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Checks whether the configuration store name is available for use. + /// + /// [OpenAPI] Operations_CheckNameAvailability=>POST:"/subscriptions/{subscriptionId}/providers/Microsoft.AppConfiguration/checkNameAvailability" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzAppConfigurationStoreNameAvailability_CheckExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Checks whether the configuration store name is available for use.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class TestAzAppConfigurationStoreNameAvailability_CheckExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters _checkNameAvailabilityParametersBody= new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.CheckNameAvailabilityParameters(); + + /// Parameters used for checking whether a resource name is available. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters CheckNameAvailabilityParametersBody { get => this._checkNameAvailabilityParametersBody; set => this._checkNameAvailabilityParametersBody = value; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// The name to check for availability. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name to check for availability.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name to check for availability.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + public string Name { get => CheckNameAvailabilityParametersBody.Name ?? null; set => CheckNameAvailabilityParametersBody.Name = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _subscriptionId; + + /// The Microsoft Azure subscription ID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Microsoft Azure subscription ID.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Microsoft Azure subscription ID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OperationsCheckNameAvailability' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsCheckNameAvailability(SubscriptionId, CheckNameAvailabilityParametersBody, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,body=CheckNameAvailabilityParametersBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public TestAzAppConfigurationStoreNameAvailability_CheckExpanded() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, body=CheckNameAvailabilityParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, body=CheckNameAvailabilityParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/TestAzAppConfigurationStoreNameAvailability_CheckViaIdentity.cs b/src/AppConfiguration/generated/cmdlets/TestAzAppConfigurationStoreNameAvailability_CheckViaIdentity.cs new file mode 100644 index 000000000000..e04cfb100493 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/TestAzAppConfigurationStoreNameAvailability_CheckViaIdentity.cs @@ -0,0 +1,386 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Checks whether the configuration store name is available for use. + /// + /// [OpenAPI] Operations_CheckNameAvailability=>POST:"/subscriptions/{subscriptionId}/providers/Microsoft.AppConfiguration/checkNameAvailability" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzAppConfigurationStoreNameAvailability_CheckViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Checks whether the configuration store name is available for use.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class TestAzAppConfigurationStoreNameAvailability_CheckViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters _checkNameAvailabilityParameter; + + /// Parameters used for checking whether a resource name is available. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Parameters used for checking whether a resource name is available.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Parameters used for checking whether a resource name is available.", + SerializedName = @"checkNameAvailabilityParameters", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters) })] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters CheckNameAvailabilityParameter { get => this._checkNameAvailabilityParameter; set => this._checkNameAvailabilityParameter = value; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OperationsCheckNameAvailability' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.OperationsCheckNameAvailabilityViaIdentity(InputObject.Id, CheckNameAvailabilityParameter, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.OperationsCheckNameAvailability(InputObject.SubscriptionId ?? null, CheckNameAvailabilityParameter, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=CheckNameAvailabilityParameter}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public TestAzAppConfigurationStoreNameAvailability_CheckViaIdentity() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=CheckNameAvailabilityParameter }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=CheckNameAvailabilityParameter }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/TestAzAppConfigurationStoreNameAvailability_CheckViaIdentityExpanded.cs b/src/AppConfiguration/generated/cmdlets/TestAzAppConfigurationStoreNameAvailability_CheckViaIdentityExpanded.cs new file mode 100644 index 000000000000..8214c55b31c2 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/TestAzAppConfigurationStoreNameAvailability_CheckViaIdentityExpanded.cs @@ -0,0 +1,390 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Checks whether the configuration store name is available for use. + /// + /// [OpenAPI] Operations_CheckNameAvailability=>POST:"/subscriptions/{subscriptionId}/providers/Microsoft.AppConfiguration/checkNameAvailability" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzAppConfigurationStoreNameAvailability_CheckViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Checks whether the configuration store name is available for use.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class TestAzAppConfigurationStoreNameAvailability_CheckViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters _checkNameAvailabilityParametersBody= new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.CheckNameAvailabilityParameters(); + + /// Parameters used for checking whether a resource name is available. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters CheckNameAvailabilityParametersBody { get => this._checkNameAvailabilityParametersBody; set => this._checkNameAvailabilityParametersBody = value; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// The name to check for availability. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name to check for availability.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name to check for availability.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + public string Name { get => CheckNameAvailabilityParametersBody.Name ?? null; set => CheckNameAvailabilityParametersBody.Name = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OperationsCheckNameAvailability' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.OperationsCheckNameAvailabilityViaIdentity(InputObject.Id, CheckNameAvailabilityParametersBody, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.OperationsCheckNameAvailability(InputObject.SubscriptionId ?? null, CheckNameAvailabilityParametersBody, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=CheckNameAvailabilityParametersBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet + /// class. + /// + public TestAzAppConfigurationStoreNameAvailability_CheckViaIdentityExpanded() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=CheckNameAvailabilityParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=CheckNameAvailabilityParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/UpdateAzAppConfigurationStore_Update.cs b/src/AppConfiguration/generated/cmdlets/UpdateAzAppConfigurationStore_Update.cs new file mode 100644 index 000000000000..4a43188ff49c --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/UpdateAzAppConfigurationStore_Update.cs @@ -0,0 +1,479 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Updates a configuration store with the specified parameters. + /// + /// [OpenAPI] ConfigurationStores_Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzAppConfigurationStore_Update", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Updates a configuration store with the specified parameters.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class UpdateAzAppConfigurationStore_Update : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters _configStoreUpdateParameter; + + /// The parameters for updating a configuration store. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parameters for updating a configuration store.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parameters for updating a configuration store.", + SerializedName = @"configStoreUpdateParameters", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters) })] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters ConfigStoreUpdateParameter { get => this._configStoreUpdateParameter; set => this._configStoreUpdateParameter = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the configuration store. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the configuration store.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the configuration store.", + SerializedName = @"configStoreName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group to which the container registry belongs. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group to which the container registry belongs.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group to which the container registry belongs.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The Microsoft Azure subscription ID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Microsoft Azure subscription ID.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Microsoft Azure subscription ID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzAppConfigurationStore_Update + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets.UpdateAzAppConfigurationStore_Update Clone() + { + var clone = new UpdateAzAppConfigurationStore_Update(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + clone.ConfigStoreUpdateParameter = this.ConfigStoreUpdateParameter; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConfigurationStoresUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConfigurationStoresUpdate(SubscriptionId, ResourceGroupName, Name, ConfigStoreUpdateParameter, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name,body=ConfigStoreUpdateParameter}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public UpdateAzAppConfigurationStore_Update() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=ConfigStoreUpdateParameter }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=ConfigStoreUpdateParameter }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/UpdateAzAppConfigurationStore_UpdateExpanded.cs b/src/AppConfiguration/generated/cmdlets/UpdateAzAppConfigurationStore_UpdateExpanded.cs new file mode 100644 index 000000000000..a281bddc0fa0 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/UpdateAzAppConfigurationStore_UpdateExpanded.cs @@ -0,0 +1,495 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Updates a configuration store with the specified parameters. + /// + /// [OpenAPI] ConfigurationStores_Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzAppConfigurationStore_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Updates a configuration store with the specified parameters.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class UpdateAzAppConfigurationStore_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters _configStoreUpdateParametersBody= new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreUpdateParameters(); + + /// The parameters for updating a configuration store. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters ConfigStoreUpdateParametersBody { get => this._configStoreUpdateParametersBody; set => this._configStoreUpdateParametersBody = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the configuration store. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the configuration store.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the configuration store.", + SerializedName = @"configStoreName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The properties for updating a configuration store. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The properties for updating a configuration store.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The properties for updating a configuration store.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters) })] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters Property { get => ConfigStoreUpdateParametersBody.Property ?? null /* object */; set => ConfigStoreUpdateParametersBody.Property = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group to which the container registry belongs. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group to which the container registry belongs.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group to which the container registry belongs.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The Microsoft Azure subscription ID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Microsoft Azure subscription ID.")] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Microsoft Azure subscription ID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// The ARM resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The ARM resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The ARM resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags Tag { get => ConfigStoreUpdateParametersBody.Tag ?? null /* object */; set => ConfigStoreUpdateParametersBody.Tag = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzAppConfigurationStore_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets.UpdateAzAppConfigurationStore_UpdateExpanded Clone() + { + var clone = new UpdateAzAppConfigurationStore_UpdateExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.ConfigStoreUpdateParametersBody = this.ConfigStoreUpdateParametersBody; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConfigurationStoresUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConfigurationStoresUpdate(SubscriptionId, ResourceGroupName, Name, ConfigStoreUpdateParametersBody, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name,body=ConfigStoreUpdateParametersBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public UpdateAzAppConfigurationStore_UpdateExpanded() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=ConfigStoreUpdateParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=ConfigStoreUpdateParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/UpdateAzAppConfigurationStore_UpdateViaIdentity.cs b/src/AppConfiguration/generated/cmdlets/UpdateAzAppConfigurationStore_UpdateViaIdentity.cs new file mode 100644 index 000000000000..2cfefcffd096 --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/UpdateAzAppConfigurationStore_UpdateViaIdentity.cs @@ -0,0 +1,458 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Updates a configuration store with the specified parameters. + /// + /// [OpenAPI] ConfigurationStores_Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzAppConfigurationStore_UpdateViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Updates a configuration store with the specified parameters.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class UpdateAzAppConfigurationStore_UpdateViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters _configStoreUpdateParameter; + + /// The parameters for updating a configuration store. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parameters for updating a configuration store.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parameters for updating a configuration store.", + SerializedName = @"configStoreUpdateParameters", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters) })] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters ConfigStoreUpdateParameter { get => this._configStoreUpdateParameter; set => this._configStoreUpdateParameter = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzAppConfigurationStore_UpdateViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets.UpdateAzAppConfigurationStore_UpdateViaIdentity Clone() + { + var clone = new UpdateAzAppConfigurationStore_UpdateViaIdentity(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.ConfigStoreUpdateParameter = this.ConfigStoreUpdateParameter; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConfigurationStoresUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ConfigurationStoresUpdateViaIdentity(InputObject.Id, ConfigStoreUpdateParameter, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ConfigStoreName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ConfigStoreName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ConfigurationStoresUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ConfigStoreName ?? null, ConfigStoreUpdateParameter, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ConfigStoreUpdateParameter}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public UpdateAzAppConfigurationStore_UpdateViaIdentity() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ConfigStoreUpdateParameter }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ConfigStoreUpdateParameter }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/cmdlets/UpdateAzAppConfigurationStore_UpdateViaIdentityExpanded.cs b/src/AppConfiguration/generated/cmdlets/UpdateAzAppConfigurationStore_UpdateViaIdentityExpanded.cs new file mode 100644 index 000000000000..bea76c2076fd --- /dev/null +++ b/src/AppConfiguration/generated/cmdlets/UpdateAzAppConfigurationStore_UpdateViaIdentityExpanded.cs @@ -0,0 +1,474 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + /// Updates a configuration store with the specified parameters. + /// + /// [OpenAPI] ConfigurationStores_Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzAppConfigurationStore_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore))] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Description(@"Updates a configuration store with the specified parameters.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Generated] + public partial class UpdateAzAppConfigurationStore_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.AppConfigurationManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.ClientAPI; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters _configStoreUpdateParametersBody= new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ConfigurationStoreUpdateParameters(); + + /// The parameters for updating a configuration store. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters ConfigStoreUpdateParametersBody { get => this._configStoreUpdateParametersBody; set => this._configStoreUpdateParametersBody = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } + + /// SendAsync Pipeline Steps to be prepended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.HttpPipeline Pipeline { get; set; } + + /// The properties for updating a configuration store. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The properties for updating a configuration store.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The properties for updating a configuration store.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters) })] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters Property { get => ConfigStoreUpdateParametersBody.Property ?? null /* object */; set => ConfigStoreUpdateParametersBody.Property = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Uri Proxy { get; set; } + + /// Credentials for a proxy server to use for the remote call + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } + + /// Use the default credentials for the proxy + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// The ARM resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The ARM resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The ARM resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags Tag { get => ConfigStoreUpdateParametersBody.Tag ?? null /* object */; set => ConfigStoreUpdateParametersBody.Tag = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzAppConfigurationStore_UpdateViaIdentityExpanded + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Cmdlets.UpdateAzAppConfigurationStore_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzAppConfigurationStore_UpdateViaIdentityExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.ConfigStoreUpdateParametersBody = this.ConfigStoreUpdateParametersBody; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func messageData) + { + using( NoSynchronizationContext ) + { + if (token.IsCancellationRequested) + { + return ; + } + + switch ( id ) + { + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConfigurationStoresUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token); + } + } + } + } + catch (global::System.AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach( var innerException in aggregateException.Flatten().InnerExceptions ) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + } + catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + // Write exception out to error channel. + WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); + } + finally + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordEnd).Wait(); + } + } + + /// Performs execution of the command, working asynchronously if required. + /// + /// A that will be complete when handling of the method is completed. + /// + protected async global::System.Threading.Tasks.Task ProcessRecordAsync() + { + using( NoSynchronizationContext ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ConfigurationStoresUpdateViaIdentity(InputObject.Id, ConfigStoreUpdateParametersBody, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ConfigStoreName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ConfigStoreName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ConfigurationStoresUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ConfigStoreName ?? null, ConfigStoreUpdateParametersBody, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ConfigStoreUpdateParametersBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public UpdateAzAppConfigurationStore_UpdateViaIdentityExpanded() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ConfigStoreUpdateParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ConfigStoreUpdateParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/AsyncCommandRuntime.cs b/src/AppConfiguration/generated/runtime/AsyncCommandRuntime.cs new file mode 100644 index 000000000000..303c04bf7536 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/AsyncCommandRuntime.cs @@ -0,0 +1,828 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + using System.Management.Automation; + using System.Management.Automation.Host; + using System.Threading; + using System.Linq; + + internal interface IAsyncCommandRuntimeExtensions + { + Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep func); + System.Collections.Generic.IEnumerable Wrap(System.Collections.Generic.IEnumerable funcs); + + T ExecuteSync(System.Func step); + } + + public class AsyncCommandRuntime : System.Management.Automation.ICommandRuntime2, IAsyncCommandRuntimeExtensions, System.IDisposable + { + private ICommandRuntime2 originalCommandRuntime; + private System.Threading.Thread originalThread; + public bool AllowInteractive { get; set; } = false; + + public CancellationToken cancellationToken; + SemaphoreSlim semaphore = new SemaphoreSlim(1, 1); + ManualResetEventSlim readyToRun = new ManualResetEventSlim(false); + ManualResetEventSlim completed = new ManualResetEventSlim(false); + + System.Action runOnMainThread; + + private System.Management.Automation.PSCmdlet cmdlet; + + internal AsyncCommandRuntime(System.Management.Automation.PSCmdlet cmdlet, CancellationToken cancellationToken) + { + this.originalCommandRuntime = cmdlet.CommandRuntime as ICommandRuntime2; + this.originalThread = System.Threading.Thread.CurrentThread; + this.cancellationToken = cancellationToken; + this.cmdlet = cmdlet; + cmdlet.CommandRuntime = this; + } + + public PSHost Host => this.originalCommandRuntime.Host; + + public PSTransactionContext CurrentPSTransaction => this.originalCommandRuntime.CurrentPSTransaction; + + private void CheckForInteractive() + { + // This is an interactive call -- if we are not on the original thread, this will only work if this was done at ACR creation time; + if (!AllowInteractive) + { + throw new System.Exception("AsyncCommandRuntime is not configured for interactive calls"); + } + } + private void WaitOurTurn() + { + // wait for our turn to play + semaphore?.Wait(cancellationToken); + + // ensure that completed is not set + completed.Reset(); + } + + private void WaitForCompletion() + { + // wait for the result (or cancellation!) + WaitHandle.WaitAny(new[] { cancellationToken.WaitHandle, completed?.WaitHandle }); + + // let go of the semaphore + semaphore?.Release(); + + } + + public bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target, string action) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target, action); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target, action); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + ShouldProcessReason reason = ShouldProcessReason.None; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out reason); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + shouldProcessReason = reason; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void ThrowTerminatingError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.ThrowTerminatingError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.ThrowTerminatingError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool TransactionAvailable() + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.TransactionAvailable(); + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.TransactionAvailable(); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteCommandDetail(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteCommandDetail(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteCommandDetail(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteDebug(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteDebug(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteDebug(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteInformation(InformationRecord informationRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteInformation(informationRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteInformation(informationRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline, bool enumerateCollection) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(long sourceId, ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(sourceId, progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(sourceId, progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteVerbose(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteVerbose(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteVerbose(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteWarning(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteWarning(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteWarning(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void Wait(System.Threading.Tasks.Task ProcessRecordAsyncTask, System.Threading.CancellationToken cancellationToken) + { + do + { + WaitHandle.WaitAny(new[] { readyToRun.WaitHandle, ((System.IAsyncResult)ProcessRecordAsyncTask).AsyncWaitHandle }); + if (readyToRun.IsSet) + { + // reset the request for the next time + readyToRun.Reset(); + + // run the delegate on this thread + runOnMainThread(); + + // tell the originator everything is complete + completed.Set(); + } + } + while (!ProcessRecordAsyncTask.IsCompleted); + if (ProcessRecordAsyncTask.IsFaulted) + { + // don't unwrap a Aggregate Exception -- we'll lose the stack trace of the actual exception. + // if( ProcessRecordAsyncTask.Exception is System.AggregateException aggregate ) { + // throw aggregate.InnerException; + // } + throw ProcessRecordAsyncTask.Exception; + } + } + public Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep func) => func.Target.GetType().Name != "Closure" ? func : (p1, p2, p3) => ExecuteSync>(() => func(p1, p2, p3)); + public System.Collections.Generic.IEnumerable Wrap(System.Collections.Generic.IEnumerable funcs) => funcs?.Select(Wrap); + + public T ExecuteSync(System.Func step) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return step(); + } + + T result = default(T); + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + // set the function to run + runOnMainThread = () => { result = step(); }; + // tell the main thread to go ahead + readyToRun.Set(); + // wait for the result (or cancellation!) + WaitForCompletion(); + // return + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void Dispose() + { + if (cmdlet != null) + { + cmdlet.CommandRuntime = this.originalCommandRuntime; + cmdlet = null; + } + + semaphore?.Dispose(); + semaphore = null; + readyToRun?.Dispose(); + readyToRun = null; + completed?.Dispose(); + completed = null; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/AsyncJob.cs b/src/AppConfiguration/generated/runtime/AsyncJob.cs new file mode 100644 index 000000000000..51dea6d4895e --- /dev/null +++ b/src/AppConfiguration/generated/runtime/AsyncJob.cs @@ -0,0 +1,270 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + using System.Management.Automation; + using System.Management.Automation.Host; + using System.Threading; + + using System.Threading.Tasks; + + public class LongRunningJobCancelledException : System.Exception + { + public LongRunningJobCancelledException(string message) : base(message) + { + + } + } + + public class AsyncJob : Job, System.Management.Automation.ICommandRuntime2 + { + const int MaxRecords = 1000; + + private string _statusMessage = string.Empty; + + public override string StatusMessage => _statusMessage; + + public override bool HasMoreData => Output.Count > 0 || Progress.Count > 0 || Error.Count > 0 || Warning.Count > 0 || Verbose.Count > 0 || Debug.Count > 0; + + public override string Location => "localhost"; + + public PSHost Host => originalCommandRuntime.Host; + + public PSTransactionContext CurrentPSTransaction => originalCommandRuntime.CurrentPSTransaction; + + public override void StopJob() + { + Cancel(); + } + + private readonly PSCmdlet cmdlet; + private readonly ICommandRuntime2 originalCommandRuntime; + private readonly System.Threading.Thread originalThread; + + private void CheckForInteractive() + { + // This is an interactive call -- We should never allow interactivity in AsnycJob cmdlets. + throw new System.Exception("Cmdlets in AsyncJob; interactive calls are not permitted."); + } + private bool IsJobDone => CancellationToken.IsCancellationRequested || this.JobStateInfo.State == JobState.Failed || this.JobStateInfo.State == JobState.Stopped || this.JobStateInfo.State == JobState.Stopping || this.JobStateInfo.State == JobState.Completed; + + private readonly System.Action Cancel; + private readonly CancellationToken CancellationToken; + + internal AsyncJob(PSCmdlet cmdlet, string line, string name, CancellationToken cancellationToken, System.Action cancelMethod) : base(line, name) + { + SetJobState(JobState.NotStarted); + // know how to cancel/check for cancelation + this.CancellationToken = cancellationToken; + this.Cancel = cancelMethod; + + // we might need these. + this.originalCommandRuntime = cmdlet.CommandRuntime as ICommandRuntime2; + this.originalThread = System.Threading.Thread.CurrentThread; + + // the instance of the cmdlet we're going to run + this.cmdlet = cmdlet; + + // set the command runtime to the AsyncJob + cmdlet.CommandRuntime = this; + } + + /// + /// Monitors the task (which should be ProcessRecordAsync) to control + /// the lifetime of the job itself + /// + /// + public void Monitor(Task task) + { + SetJobState(JobState.Running); + task.ContinueWith(antecedent => + { + if (antecedent.IsCanceled) + { + // if the task was canceled, we're just going to call it completed. + SetJobState(JobState.Completed); + } + else if (antecedent.IsFaulted) + { + foreach (var innerException in antecedent.Exception.Flatten().InnerExceptions) + { + WriteError(new System.Management.Automation.ErrorRecord(innerException, string.Empty, System.Management.Automation.ErrorCategory.NotSpecified, null)); + } + + // a fault indicates an actual failure + SetJobState(JobState.Failed); + } + else + { + // otherwiser it's a completed state. + SetJobState(JobState.Completed); + } + }, CancellationToken); + } + + private void CheckForCancellation() + { + if (IsJobDone) + { + throw new LongRunningJobCancelledException("Long running job is canceled or stopping, continuation of the cmdlet is not permitted."); + } + } + + public void WriteInformation(InformationRecord informationRecord) + { + CheckForCancellation(); + + this.Information.Add(informationRecord); + } + + public bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll) + { + CheckForInteractive(); + return false; + } + + public void WriteDebug(string text) + { + _statusMessage = text; + CheckForCancellation(); + + if (Debug.IsOpen && Debug.Count < MaxRecords) + { + Debug.Add(new DebugRecord(text)); + } + } + + public void WriteError(ErrorRecord errorRecord) + { + if (Error.IsOpen) + { + Error.Add(errorRecord); + } + } + + public void WriteObject(object sendToPipeline) + { + CheckForCancellation(); + + if (Output.IsOpen) + { + Output.Add(new PSObject(sendToPipeline)); + } + } + + public void WriteObject(object sendToPipeline, bool enumerateCollection) + { + CheckForCancellation(); + + if (enumerateCollection && sendToPipeline is System.Collections.IEnumerable enumerable) + { + foreach (var item in enumerable) + { + WriteObject(item); + } + } + else + { + WriteObject(sendToPipeline); + } + } + + public void WriteProgress(ProgressRecord progressRecord) + { + CheckForCancellation(); + + if (Progress.IsOpen && Progress.Count < MaxRecords) + { + Progress.Add(progressRecord); + } + } + + public void WriteProgress(long sourceId, ProgressRecord progressRecord) + { + CheckForCancellation(); + + if (Progress.IsOpen && Progress.Count < MaxRecords) + { + Progress.Add(progressRecord); + } + } + + public void WriteVerbose(string text) + { + CheckForCancellation(); + + if (Verbose.IsOpen && Verbose.Count < MaxRecords) + { + Verbose.Add(new VerboseRecord(text)); + } + } + + public void WriteWarning(string text) + { + CheckForCancellation(); + + if (Warning.IsOpen && Warning.Count < MaxRecords) + { + Warning.Add(new WarningRecord(text)); + } + } + + public void WriteCommandDetail(string text) + { + WriteVerbose(text); + } + + public bool ShouldProcess(string target) + { + CheckForInteractive(); + return false; + } + + public bool ShouldProcess(string target, string action) + { + CheckForInteractive(); + return false; + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) + { + CheckForInteractive(); + return false; + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) + { + CheckForInteractive(); + shouldProcessReason = ShouldProcessReason.None; + return false; + } + + public bool ShouldContinue(string query, string caption) + { + CheckForInteractive(); + return false; + } + + public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) + { + CheckForInteractive(); + return false; + } + + public bool TransactionAvailable() + { + // interactivity required? + return false; + } + + public void ThrowTerminatingError(ErrorRecord errorRecord) + { + if (Error.IsOpen) + { + Error.Add(errorRecord); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/AsyncOperationResponse.cs b/src/AppConfiguration/generated/runtime/AsyncOperationResponse.cs new file mode 100644 index 000000000000..5d087f2f6d9f --- /dev/null +++ b/src/AppConfiguration/generated/runtime/AsyncOperationResponse.cs @@ -0,0 +1,177 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + [System.ComponentModel.TypeConverter(typeof(AsyncOperationResponseTypeConverter))] + public class AsyncOperationResponse + { + private string _target; + public string Target { get => _target; set => _target = value; } + public AsyncOperationResponse() + { + } + internal AsyncOperationResponse(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json) + { + // pull target + { Target = If(json?.PropertyT("target"), out var _v) ? (string)_v : (string)Target; } + } + public string ToJsonString() + { + return $"{{ \"target\" : \"{this.Target}\" }}"; + } + + public static AsyncOperationResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject json ? new AsyncOperationResponse(json) : null; + } + + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static AsyncOperationResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + } + + public partial class AsyncOperationResponseTypeConverter : System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static object ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(AsyncOperationResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AsyncOperationResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString()); ; + } + catch + { + // Unable to use JSON pattern + } + + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as System.Management.Automation.PSObject).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as global::System.Collections.IDictionary).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs new file mode 100644 index 000000000000..424f8fdf2ead --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs @@ -0,0 +1,113 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "CmdletSurface")] + [DoNotExport] + public class ExportCmdletSurface : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string CmdletFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string OutputFolder { get; set; } + + [Parameter] + public bool IncludeGeneralParameters { get; set; } + + [Parameter] + public bool UseExpandedFormat { get; set; } + + protected override void ProcessRecord() + { + try + { + var variants = GetScriptCmdlets(this, CmdletFolder) + .SelectMany(fi => fi.ToVariants()) + .Where(v => !v.IsDoNotExport) + .ToArray(); + var allProfiles = variants.SelectMany(v => v.Profiles).Distinct().ToArray(); + var profileGroups = allProfiles.Any() + ? variants + .SelectMany(v => (v.Profiles.Any() ? v.Profiles : allProfiles).Select(p => (profile: p, variant: v))) + .GroupBy(pv => pv.profile) + .Select(pvg => new ProfileGroup(pvg.Select(pv => pv.variant).ToArray(), pvg.Key)) + : new[] { new ProfileGroup(variants) }; + foreach (var profileGroup in profileGroups) + { + var variantGroups = profileGroup.Variants + .GroupBy(v => new { v.CmdletName }) + .Select(vg => new VariantGroup(ModuleName, vg.Key.CmdletName, vg.Select(v => v).ToArray(), String.Empty, profileGroup.ProfileName)); + var sb = UseExpandedFormat ? ExpandedFormat(variantGroups) : CondensedFormat(variantGroups); + Directory.CreateDirectory(OutputFolder); + File.WriteAllText(Path.Combine(OutputFolder, $"CmdletSurface-{profileGroup.ProfileName}.md"), sb.ToString()); + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private StringBuilder ExpandedFormat(IEnumerable variantGroups) + { + var sb = new StringBuilder(); + foreach (var variantGroup in variantGroups.OrderBy(vg => vg.CmdletName)) + { + sb.Append($"### {variantGroup.CmdletName}{Environment.NewLine}"); + var parameterGroups = variantGroup.ParameterGroups + .Where(pg => !pg.DontShow && (IncludeGeneralParameters || (pg.OrderCategory != ParameterCategory.Azure && pg.OrderCategory != ParameterCategory.Runtime))); + foreach (var parameterGroup in parameterGroups) + { + sb.Append($" - {parameterGroup.ParameterName} `{parameterGroup.ParameterType.ToSyntaxTypeName()}`{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + private StringBuilder CondensedFormat(IEnumerable variantGroups) + { + var sb = new StringBuilder(); + var condensedGroups = variantGroups + .GroupBy(vg => vg.CmdletNoun) + .Select(vgg => ( + CmdletNoun: vgg.Key, + CmdletVerbs: vgg.Select(vg => vg.CmdletVerb).OrderBy(cv => cv).ToArray(), + ParameterGroups: vgg.SelectMany(vg => vg.ParameterGroups).DistinctBy(p => p.ParameterName).ToArray(), + OutputTypes: vgg.SelectMany(vg => vg.OutputTypes).Select(ot => ot.Type).DistinctBy(t => t.Name).Select(t => t.ToSyntaxTypeName()).ToArray())) + .OrderBy(vg => vg.CmdletNoun); + foreach (var condensedGroup in condensedGroups) + { + sb.Append($"### {condensedGroup.CmdletNoun} [{String.Join(", ", condensedGroup.CmdletVerbs)}] `{String.Join(", ", condensedGroup.OutputTypes)}`{Environment.NewLine}"); + var parameterGroups = condensedGroup.ParameterGroups + .Where(pg => !pg.DontShow && (IncludeGeneralParameters || (pg.OrderCategory != ParameterCategory.Azure && pg.OrderCategory != ParameterCategory.Runtime))); + foreach (var parameterGroup in parameterGroups) + { + sb.Append($" - {parameterGroup.ParameterName} `{parameterGroup.ParameterType.ToSyntaxTypeName()}`{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs new file mode 100644 index 000000000000..be7ddf177165 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs @@ -0,0 +1,74 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "ExampleStub")] + [DoNotExport] + public class ExportExampleStub : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string OutputFolder { get; set; } + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + var exportDirectories = Directory.GetDirectories(ExportsFolder); + if (!exportDirectories.Any()) + { + exportDirectories = new[] { ExportsFolder }; + } + + var exampleText = String.Join(String.Empty, DefaultExampleHelpInfos.Select(ehi => ehi.ToHelpExampleOutput())); + foreach (var exportDirectory in exportDirectories) + { + var outputFolder = OutputFolder; + if (exportDirectory != ExportsFolder) + { + outputFolder = Path.Combine(OutputFolder, Path.GetFileName(exportDirectory)); + Directory.CreateDirectory(outputFolder); + } + + var cmdletFilePaths = GetScriptCmdlets(exportDirectory).Select(fi => Path.Combine(outputFolder, $"{fi.Name}.md")).ToArray(); + var currentExamplesFilePaths = Directory.GetFiles(outputFolder).ToArray(); + // Remove examples of non-existing cmdlets + var removedCmdletFilePaths = currentExamplesFilePaths.Except(cmdletFilePaths); + foreach (var removedCmdletFilePath in removedCmdletFilePaths) + { + File.Delete(removedCmdletFilePath); + } + + // Only create example stubs if they don't exist + foreach (var cmdletFilePath in cmdletFilePaths.Except(currentExamplesFilePaths)) + { + File.WriteAllText(cmdletFilePath, exampleText); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs new file mode 100644 index 000000000000..c1f0d0b5ae10 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs @@ -0,0 +1,99 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "FormatPs1xml")] + [DoNotExport] + public class ExportFormatPs1xml : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string FilePath { get; set; } + + private const string ModelNamespace = @"Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models"; + private const string SupportNamespace = @"Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support"; + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + protected override void ProcessRecord() + { + try + { + var viewModels = GetFilteredViewParameters().Select(CreateViewModel).ToList(); + var ps1xml = new Configuration + { + ViewDefinitions = new ViewDefinitions + { + Views = viewModels + } + }; + File.WriteAllText(FilePath, ps1xml.ToXmlString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static IEnumerable GetFilteredViewParameters() + { + //https://stackoverflow.com/a/79738/294804 + //https://stackoverflow.com/a/949285/294804 + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass + && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace)) + && !t.GetCustomAttributes().Any()); + return types.Select(t => new ViewParameters(t, t.GetProperties() + .Select(p => new PropertyFormat(p)) + .Where(pf => !pf.Property.GetCustomAttributes().Any() + && (!IsAzure || pf.Property.Name != "Id") + && (pf.FormatTable != null || (pf.Origin != PropertyOrigin.Inlined && pf.Property.PropertyType.IsPsSimple()))) + .OrderByDescending(pf => pf.Index.HasValue) + .ThenBy(pf => pf.Index) + .ThenByDescending(pf => pf.Origin.HasValue) + .ThenBy(pf => pf.Origin))).Where(vp => vp.Properties.Any()); + } + + private static View CreateViewModel(ViewParameters viewParameters) + { + var entries = viewParameters.Properties.Select(pf => + (TableColumnHeader: new TableColumnHeader { Label = pf.Label, Width = pf.Width }, + TableColumnItem: new TableColumnItem { PropertyName = pf.Property.Name })).ToArray(); + + return new View + { + Name = viewParameters.Type.FullName, + ViewSelectedBy = new ViewSelectedBy + { + TypeName = viewParameters.Type.FullName + }, + TableControl = new TableControl + { + TableHeaders = new TableHeaders + { + TableColumnHeaders = entries.Select(e => e.TableColumnHeader).ToList() + }, + TableRowEntries = new TableRowEntries + { + TableRowEntry = new TableRowEntry + { + TableColumnItems = new TableColumnItems + { + TableItems = entries.Select(e => e.TableColumnItem).ToList() + } + } + } + } + }; + } + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs new file mode 100644 index 000000000000..a7c0ad94f383 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.MarkdownRenderer; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "HelpMarkdown")] + [DoNotExport] + public class ExportHelpMarkdown : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSModuleInfo ModuleInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] FunctionInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] HelpInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + protected override void ProcessRecord() + { + try + { + var helpInfos = HelpInfo.Select(hi => hi.ToPsHelpInfo()); + var variantGroups = FunctionInfo.Select(fi => fi.BaseObject).Cast() + .Join(helpInfos, fi => fi.Name, phi => phi.CmdletName, (fi, phi) => fi.ToVariants(phi)) + .Select(va => new VariantGroup(ModuleInfo.Name, va.First().CmdletName, va, String.Empty)); + WriteMarkdowns(variantGroups, ModuleInfo.ToModuleInfo(), DocsFolder, ExamplesFolder); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs new file mode 100644 index 000000000000..e0aedfa9c465 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs @@ -0,0 +1,117 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; +using System.Text; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "ModelSurface")] + [DoNotExport] + public class ExportModelSurface : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string OutputFolder { get; set; } + + [Parameter] + public bool UseExpandedFormat { get; set; } + + private const string ModelNamespace = @"Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models"; + private const string SupportNamespace = @"Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Support"; + + protected override void ProcessRecord() + { + try + { + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace))); + var typeInfos = types.Select(t => new ModelTypeInfo + { + Type = t, + TypeName = t.Name, + Properties = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => !p.GetIndexParameters().Any()).OrderBy(p => p.Name).ToArray(), + NamespaceGroup = t.Namespace.Split('.').LastOrDefault().EmptyIfNull() + }).Where(mti => mti.Properties.Any()); + var sb = UseExpandedFormat ? ExpandedFormat(typeInfos) : CondensedFormat(typeInfos); + Directory.CreateDirectory(OutputFolder); + File.WriteAllText(Path.Combine(OutputFolder, "ModelSurface.md"), sb.ToString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static StringBuilder ExpandedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + foreach (var typeInfo in typeInfos.OrderBy(mti => mti.TypeName).ThenBy(mti => mti.NamespaceGroup)) + { + sb.Append($"### {typeInfo.TypeName} [{typeInfo.NamespaceGroup}]{Environment.NewLine}"); + foreach (var property in typeInfo.Properties) + { + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}`{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + private static StringBuilder CondensedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + var typeGroups = typeInfos + .GroupBy(mti => mti.TypeName) + .Select(tig => ( + Types: tig.Select(mti => mti.Type).ToArray(), + TypeName: tig.Key, + Properties: tig.SelectMany(mti => mti.Properties).DistinctBy(p => p.Name).OrderBy(p => p.Name).ToArray(), + NamespaceGroups: tig.Select(mti => mti.NamespaceGroup).OrderBy(ng => ng).ToArray() + )) + .OrderBy(tg => tg.TypeName); + foreach (var typeGroup in typeGroups) + { + var aType = typeGroup.Types.Select(GetAssociativeType).FirstOrDefault(t => t != null); + var aText = aType != null ? $@" \<{aType.ToSyntaxTypeName()}\>" : String.Empty; + sb.Append($"### {typeGroup.TypeName}{aText} [{String.Join(", ", typeGroup.NamespaceGroups)}]{Environment.NewLine}"); + foreach (var property in typeGroup.Properties) + { + var propertyAType = GetAssociativeType(property.PropertyType); + var propertyAText = propertyAType != null ? $" <{propertyAType.ToSyntaxTypeName()}>" : String.Empty; + var enumNames = GetEnumFieldNames(property.PropertyType.Unwrap()); + var enumNamesText = enumNames.Any() ? $" **{{{String.Join(", ", enumNames)}}}**" : String.Empty; + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}{propertyAText}`{enumNamesText}{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + //https://stackoverflow.com/a/4963190/294804 + private static Type GetAssociativeType(Type type) => + type.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>))?.GetGenericArguments().First(); + + private static string[] GetEnumFieldNames(Type type) => + type.IsValueType && !type.IsPrimitive && type != typeof(decimal) && type != typeof(DateTime) + ? type.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.FieldType == type).Select(p => p.Name).ToArray() + : new string[] { }; + + private class ModelTypeInfo + { + public Type Type { get; set; } + public string TypeName { get; set; } + public PropertyInfo[] Properties { get; set; } + public string NamespaceGroup { get; set; } + } + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs new file mode 100644 index 000000000000..eb501fed7c06 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs @@ -0,0 +1,159 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.PsHelpers; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.MarkdownRenderer; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.PsProxyTypeExtensions; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "ProxyCmdlet", DefaultParameterSetName = "Docs")] + [DoNotExport] + public class ExportProxyCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string[] ModulePath { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string InternalFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [AllowEmptyString] + public string ModuleDescription { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + public Guid ModuleGuid { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "NoDocs")] + public SwitchParameter ExcludeDocs { get; set; } + + protected override void ProcessRecord() + { + try { + var variants = GetModuleCmdletsAndHelpInfo(this, ModulePath).SelectMany(ci => ci.ToVariants()).Where(v => !v.IsDoNotExport).ToArray(); + var allProfiles = variants.SelectMany(v => v.Profiles).Distinct().ToArray(); + var profileGroups = allProfiles.Any() + ? variants + .SelectMany(v => (v.Profiles.Any() ? v.Profiles : allProfiles).Select(p => (profile: p, variant: v))) + .GroupBy(pv => pv.profile) + .Select(pvg => new ProfileGroup(pvg.Select(pv => pv.variant).ToArray(), pvg.Key)) + : new[] { new ProfileGroup(variants) }; + var variantGroups = profileGroups.SelectMany(pg => pg.Variants + .GroupBy(v => new { v.CmdletName, v.IsInternal }) + .Select(vg => new VariantGroup(ModuleName, vg.Key.CmdletName, vg.Select(v => v).ToArray(), + Path.Combine(vg.Key.IsInternal ? InternalFolder : ExportsFolder, pg.ProfileFolder), pg.ProfileName, isInternal: vg.Key.IsInternal))) + .ToArray(); + + foreach (var variantGroup in variantGroups) + { + var parameterGroups = variantGroup.ParameterGroups.ToList(); + var isValidProfile = !String.IsNullOrEmpty(variantGroup.ProfileName) && variantGroup.ProfileName != NoProfiles; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, variantGroup.ProfileName) : ExamplesFolder; + var markdownInfo = new MarkdownHelpInfo(variantGroup, examplesFolder); + List examples = new List(); + foreach (var it in markdownInfo.Examples) + { + examples.Add(it); + } + variantGroup.HelpInfo.Examples = examples.ToArray(); + var sb = new StringBuilder(); + sb.Append(@" +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- +"); + sb.Append($"{Environment.NewLine}"); + sb.Append(variantGroup.ToHelpCommentOutput()); + sb.Append($"function {variantGroup.CmdletName} {{{Environment.NewLine}"); + sb.Append(variantGroup.Aliases.ToAliasOutput()); + sb.Append(variantGroup.OutputTypes.ToOutputTypeOutput()); + sb.Append(variantGroup.ToCmdletBindingOutput()); + sb.Append(variantGroup.ProfileName.ToProfileOutput()); + + sb.Append("param("); + sb.Append($"{(parameterGroups.Any() ? Environment.NewLine : String.Empty)}"); + foreach (var parameterGroup in parameterGroups) + { + var parameters = parameterGroup.HasAllVariants ? parameterGroup.Parameters.Take(1) : parameterGroup.Parameters; + foreach (var parameter in parameters) + { + sb.Append(parameter.ToParameterOutput(variantGroup.HasMultipleVariants, parameterGroup.HasAllVariants)); + } + sb.Append(parameterGroup.Aliases.ToAliasOutput(true)); + sb.Append(parameterGroup.HasValidateNotNull.ToValidateNotNullOutput()); + sb.Append(parameterGroup.CompleterInfo.ToArgumentCompleterOutput()); + sb.Append(parameterGroup.OrderCategory.ToParameterCategoryOutput()); + sb.Append(parameterGroup.InfoAttribute.ToInfoOutput(parameterGroup.ParameterType)); + sb.Append(parameterGroup.ToDefaultInfoOutput()); + sb.Append(parameterGroup.ParameterType.ToParameterTypeOutput()); + sb.Append(parameterGroup.Description.ToParameterDescriptionOutput()); + sb.Append(parameterGroup.ParameterName.ToParameterNameOutput(parameterGroups.IndexOf(parameterGroup) == parameterGroups.Count - 1)); + } + sb.Append($"){Environment.NewLine}{Environment.NewLine}"); + + sb.Append(variantGroup.ToBeginOutput()); + sb.Append(variantGroup.ToProcessOutput()); + sb.Append(variantGroup.ToEndOutput()); + + sb.Append($"}}{Environment.NewLine}"); + + Directory.CreateDirectory(variantGroup.OutputFolder); + File.WriteAllText(variantGroup.FilePath, sb.ToString()); + + File.AppendAllText(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"), sb.ToString()); + } + + if (!ExcludeDocs) + { + var moduleInfo = new PsModuleHelpInfo(ModuleName, ModuleGuid, ModuleDescription); + foreach (var variantGroupsByProfile in variantGroups.GroupBy(vg => vg.ProfileName)) + { + var profileName = variantGroupsByProfile.Key; + var isValidProfile = !String.IsNullOrEmpty(profileName) && profileName != NoProfiles; + var docsFolder = isValidProfile ? Path.Combine(DocsFolder, profileName) : DocsFolder; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, profileName) : ExamplesFolder; + WriteMarkdowns(variantGroupsByProfile, moduleInfo, docsFolder, examplesFolder); + } + } + } catch (Exception ee) { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs new file mode 100644 index 000000000000..7244d1b3c5f4 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs @@ -0,0 +1,125 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "Psd1")] + [DoNotExport] + public class ExportPsd1 : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string CustomFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string Psd1Path { get; set; } + + [Parameter(Mandatory = true)] + public Guid ModuleGuid { get; set; } + + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + private const string CustomFolderRelative = "./custom"; + private const string Indent = Psd1Indent; + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + if (!Directory.Exists(CustomFolder)) + { + throw new ArgumentException($"Custom folder '{CustomFolder}' does not exist"); + } + + string version = Convert.ToString(@"0.1.4"); + // Validate the module version should be semantic version + // Following regex is official from https://semver.org/ + Regex rx = new Regex(@"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$", RegexOptions.Compiled); + if (rx.Matches(version).Count != 1) + { + throw new ArgumentException("Module-version is not a valid Semantic Version"); + } + + string previewVersion = null; + if (version.Contains('-')) + { + string[] versions = version.Split("-".ToCharArray(), 2); + version = versions[0]; + previewVersion = versions[1]; + } + + var sb = new StringBuilder(); + sb.AppendLine("@{"); + sb.AppendLine($@"{GuidStart} = '{ModuleGuid}'"); + sb.AppendLine($@"{Indent}RootModule = '{"./Az.AppConfiguration.psm1"}'"); + sb.AppendLine($@"{Indent}ModuleVersion = '{version}'"); + sb.AppendLine($@"{Indent}CompatiblePSEditions = 'Core', 'Desktop'"); + sb.AppendLine($@"{Indent}Author = '{"Microsoft Corporation"}'"); + sb.AppendLine($@"{Indent}CompanyName = '{"Microsoft Corporation"}'"); + sb.AppendLine($@"{Indent}Copyright = '{"Microsoft Corporation. All rights reserved."}'"); + sb.AppendLine($@"{Indent}Description = '{"Microsoft Azure PowerShell: AppConfiguration cmdlets"}'"); + sb.AppendLine($@"{Indent}PowerShellVersion = '5.1'"); + sb.AppendLine($@"{Indent}DotNetFrameworkVersion = '4.7.2'"); + sb.AppendLine($@"{Indent}RequiredAssemblies = '{"./bin/Az.AppConfiguration.private.dll"}'"); + + var customFormatPs1xmlFiles = Directory.GetFiles(CustomFolder) + .Where(f => f.EndsWith(".format.ps1xml")) + .Select(f => $"{CustomFolderRelative}/{Path.GetFileName(f)}"); + var formatList = customFormatPs1xmlFiles.Prepend("./Az.AppConfiguration.format.ps1xml").ToPsList(); + sb.AppendLine($@"{Indent}FormatsToProcess = {formatList}"); + + var functionInfos = GetScriptCmdlets(ExportsFolder).ToArray(); + var cmdletsList = functionInfos.Select(fi => fi.Name).Distinct().Append("*").ToPsList(); + sb.AppendLine($@"{Indent}FunctionsToExport = {cmdletsList}"); + var aliasesList = functionInfos.SelectMany(fi => fi.ScriptBlock.Attributes).ToAliasNames().Append("*").ToPsList(); + sb.AppendLine($@"{Indent}AliasesToExport = {aliasesList}"); + + sb.AppendLine($@"{Indent}PrivateData = @{{"); + sb.AppendLine($@"{Indent}{Indent}PSData = @{{"); + + if (previewVersion != null) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}Prerelease = {previewVersion}"); + } + sb.AppendLine($@"{Indent}{Indent}{Indent}Tags = {"Azure ResourceManager ARM PSModule AppConfiguration".Split(' ').ToPsList().NullIfEmpty() ?? "''"}"); + sb.AppendLine($@"{Indent}{Indent}{Indent}LicenseUri = '{"https://aka.ms/azps-license"}'"); + sb.AppendLine($@"{Indent}{Indent}{Indent}ProjectUri = '{"https://github.com/Azure/azure-powershell"}'"); + sb.AppendLine($@"{Indent}{Indent}{Indent}ReleaseNotes = ''"); + var profilesList = ""; + if (IsAzure && !String.IsNullOrEmpty(profilesList)) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}Profiles = {profilesList}"); + } + + sb.AppendLine($@"{Indent}{Indent}}}"); + sb.AppendLine($@"{Indent}}}"); + sb.AppendLine(@"}"); + + File.WriteAllText(Psd1Path, sb.ToString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs new file mode 100644 index 000000000000..d06c7c19966c --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs @@ -0,0 +1,137 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "TestStub")] + [DoNotExport] + public class ExportTestStub : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string OutputFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeGenerated { get; set; } + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + var exportDirectories = Directory.GetDirectories(ExportsFolder); + if (!exportDirectories.Any()) + { + exportDirectories = new[] { ExportsFolder }; + } + var utilFile = Path.Combine(OutputFolder, "utils.ps1"); + if (!File.Exists(utilFile)) + { + var sc = new StringBuilder(); + sc.AppendLine(@"function RandomString([bool]$allChars, [int32]$len) { + if ($allChars) { + return -join ((33..126) | Get-Random -Count $len | % {[char]$_}) + } else { + return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_}) + } +} +$env = @{} +function setupEnv() { + # Preload subscriptionId and tenant from context, which will be used in test + # as default. You could change them if needed. + $env.SubscriptionId = (Get-AzContext).Subscription.Id + $env.Tenant = (Get-AzContext).Tenant.Id + # For any resources you created for test, you should add it to $env here. + $envFile = 'env.json' + if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' + } + set-content -Path (Join-Path $PSScriptRoot $envFile) -Value (ConvertTo-Json $env) +} +function cleanupEnv() { + # Clean resources you create for testing +} +"); + File.WriteAllText(utilFile, sc.ToString()); + } + foreach (var exportDirectory in exportDirectories) + { + var outputFolder = OutputFolder; + if (exportDirectory != ExportsFolder) + { + outputFolder = Path.Combine(OutputFolder, Path.GetFileName(exportDirectory)); + Directory.CreateDirectory(outputFolder); + } + + var variantGroups = GetScriptCmdlets(exportDirectory) + .SelectMany(fi => fi.ToVariants()) + .Where(v => !v.IsDoNotExport) + .GroupBy(v => v.CmdletName) + .Select(vg => new VariantGroup(ModuleName, vg.Key, vg.Select(v => v).ToArray(), outputFolder, isTest: true)) + .Where(vtg => !File.Exists(vtg.FilePath) && (IncludeGenerated || !vtg.IsGenerated)); + + foreach (var variantGroup in variantGroups) + { + var sb = new StringBuilder(); + sb.AppendLine(@"$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath)" +); + sb.AppendLine($@"$TestRecordingFile = Join-Path $PSScriptRoot '{variantGroup.CmdletName}.Recording.json'"); + sb.AppendLine(@"$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName +"); + + sb.AppendLine($"Describe '{variantGroup.CmdletName}' {{"); + var variants = variantGroup.Variants + .Where(v => IncludeGenerated || !v.Attributes.OfType().Any()) + .ToList(); + + foreach (var variant in variants) + { + sb.AppendLine($"{Indent}It '{variant.VariantName}' -skip {{"); + sb.AppendLine($"{Indent}{Indent}{{ throw [System.NotImplementedException] }} | Should -Not -Throw"); + var variantSeparator = variants.IndexOf(variant) == variants.Count - 1 ? String.Empty : Environment.NewLine; + sb.AppendLine($"{Indent}}}{variantSeparator}"); + } + sb.AppendLine("}"); + + File.WriteAllText(variantGroup.FilePath, sb.ToString()); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs new file mode 100644 index 000000000000..58fd74bc0628 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs @@ -0,0 +1,52 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + [Cmdlet(VerbsCommon.Get, "CommonParameter")] + [OutputType(typeof(Dictionary))] + [DoNotExport] + public class GetCommonParameter : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSCmdlet PSCmdlet { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public Dictionary PSBoundParameter { get; set; } + + protected override void ProcessRecord() + { + try + { + var variants = PSCmdlet.MyInvocation.MyCommand.ToVariants(); + var commonParameterNames = variants.ToParameterGroups() + .Where(pg => pg.OrderCategory == ParameterCategory.Azure || pg.OrderCategory == ParameterCategory.Runtime) + .Select(pg => pg.ParameterName); + if (variants.Any(v => v.SupportsShouldProcess)) + { + commonParameterNames = commonParameterNames.Append("Confirm").Append("WhatIf"); + } + if (variants.Any(v => v.SupportsPaging)) + { + commonParameterNames = commonParameterNames.Append("First").Append("Skip").Append("IncludeTotalCount"); + } + + var names = commonParameterNames.ToArray(); + var keys = PSBoundParameter.Keys.Where(k => names.Contains(k)); + WriteObject(keys.ToDictionary(key => key, key => PSBoundParameter[key]), true); + } + catch (System.Exception ee) + { + System.Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs new file mode 100644 index 000000000000..e1b34a259ec5 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + [Cmdlet(VerbsCommon.Get, "ModuleGuid")] + [DoNotExport] + public class GetModuleGuid : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string Psd1Path { get; set; } + + protected override void ProcessRecord() + { + try + { + WriteObject(ReadGuidFromPsd1(Psd1Path)); + } + catch (System.Exception ee) + { + System.Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs new file mode 100644 index 000000000000..099cbc09f53d --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + [Cmdlet(VerbsCommon.Get, "ScriptCmdlet")] + [OutputType(typeof(string[]))] + [DoNotExport] + public class GetScriptCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ScriptFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeDoNotExport { get; set; } + + [Parameter] + public SwitchParameter AsAlias { get; set; } + + [Parameter] + public SwitchParameter AsFunctionInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var functionInfos = GetScriptCmdlets(this, ScriptFolder) + .Where(fi => IncludeDoNotExport || !fi.ScriptBlock.Attributes.OfType().Any()) + .ToArray(); + if (AsFunctionInfo) + { + WriteObject(functionInfos, true); + return; + } + var aliases = functionInfos.SelectMany(i => i.ScriptBlock.Attributes).ToAliasNames(); + var names = functionInfos.Select(fi => fi.Name).Distinct(); + var output = (AsAlias ? aliases : names).DefaultIfEmpty("''").ToArray(); + WriteObject(output, true); + } + catch (System.Exception ee) + { + System.Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/CollectionExtensions.cs b/src/AppConfiguration/generated/runtime/BuildTime/CollectionExtensions.cs new file mode 100644 index 000000000000..3e87ce21ee2d --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/CollectionExtensions.cs @@ -0,0 +1,20 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + internal static class CollectionExtensions + { + public static T[] NullIfEmpty(this T[] collection) => (collection?.Any() ?? false) ? collection : null; + public static IEnumerable EmptyIfNull(this IEnumerable collection) => collection ?? Enumerable.Empty(); + + // https://stackoverflow.com/a/4158364/294804 + public static IEnumerable DistinctBy(this IEnumerable collection, Func selector) => + collection.GroupBy(selector).Select(group => group.First()); + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/MarkdownRenderer.cs b/src/AppConfiguration/generated/runtime/BuildTime/MarkdownRenderer.cs new file mode 100644 index 000000000000..8ae5b637ee7b --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/MarkdownRenderer.cs @@ -0,0 +1,121 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.PsProxyOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + internal static class MarkdownRenderer + { + public static void WriteMarkdowns(IEnumerable variantGroups, PsModuleHelpInfo moduleHelpInfo, string docsFolder, string examplesFolder) + { + Directory.CreateDirectory(docsFolder); + var markdownInfos = variantGroups.Where(vg => !vg.IsInternal).Select(vg => new MarkdownHelpInfo(vg, examplesFolder)).OrderBy(mhi => mhi.CmdletName).ToArray(); + + foreach (var markdownInfo in markdownInfos) + { + var sb = new StringBuilder(); + sb.Append(markdownInfo.ToHelpMetadataOutput()); + sb.Append($"# {markdownInfo.CmdletName}{Environment.NewLine}{Environment.NewLine}"); + sb.Append($"## SYNOPSIS{Environment.NewLine}{markdownInfo.Synopsis.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## SYNTAX{Environment.NewLine}{Environment.NewLine}"); + var hasMultipleParameterSets = markdownInfo.SyntaxInfos.Length > 1; + foreach (var syntaxInfo in markdownInfo.SyntaxInfos) + { + sb.Append(syntaxInfo.ToHelpSyntaxOutput(hasMultipleParameterSets)); + } + + sb.Append($"## DESCRIPTION{Environment.NewLine}{markdownInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## EXAMPLES{Environment.NewLine}{Environment.NewLine}"); + foreach (var exampleInfo in markdownInfo.Examples) + { + sb.Append(exampleInfo.ToHelpExampleOutput()); + } + + sb.Append($"## PARAMETERS{Environment.NewLine}{Environment.NewLine}"); + foreach (var parameter in markdownInfo.Parameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + if (markdownInfo.SupportsShouldProcess) + { + foreach (var parameter in SupportsShouldProcessParameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + } + if (markdownInfo.SupportsPaging) + { + foreach (var parameter in SupportsPagingParameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + } + + sb.Append($"### CommonParameters{Environment.NewLine}This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## INPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var input in markdownInfo.Inputs) + { + sb.Append($"### {input}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## OUTPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var output in markdownInfo.Outputs) + { + sb.Append($"### {output}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## NOTES{Environment.NewLine}{Environment.NewLine}"); + sb.Append($"ALIASES{Environment.NewLine}{Environment.NewLine}"); + foreach (var alias in markdownInfo.Aliases) + { + sb.Append($"### {alias}{Environment.NewLine}{Environment.NewLine}"); + } + if (markdownInfo.ComplexInterfaceInfos.Any()) + { + sb.Append($"{ComplexParameterHeader}{Environment.NewLine}"); + } + foreach (var complexInterfaceInfo in markdownInfo.ComplexInterfaceInfos) + { + sb.Append($"{complexInterfaceInfo.ToNoteOutput(includeDashes: true, includeBackticks: true)}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## RELATED LINKS{Environment.NewLine}{Environment.NewLine}"); + foreach (var relatedLink in markdownInfo.RelatedLinks) + { + sb.Append($"{relatedLink}{Environment.NewLine}{Environment.NewLine}"); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{markdownInfo.CmdletName}.md"), sb.ToString()); + } + + WriteModulePage(moduleHelpInfo, markdownInfos, docsFolder); + } + + private static void WriteModulePage(PsModuleHelpInfo moduleInfo, MarkdownHelpInfo[] markdownInfos, string docsFolder) + { + var sb = new StringBuilder(); + sb.Append(moduleInfo.ToModulePageMetadataOutput()); + sb.Append($"# {moduleInfo.Name} Module{Environment.NewLine}"); + sb.Append($"## Description{Environment.NewLine}{moduleInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## {moduleInfo.Name} Cmdlets{Environment.NewLine}"); + foreach (var markdownInfo in markdownInfos) + { + sb.Append(markdownInfo.ToModulePageCmdletOutput()); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{moduleInfo.Name}.md"), sb.ToString()); + } + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/Models/PsFormatTypes.cs b/src/AppConfiguration/generated/runtime/BuildTime/Models/PsFormatTypes.cs new file mode 100644 index 000000000000..3b34d7f887c2 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/Models/PsFormatTypes.cs @@ -0,0 +1,138 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Xml.Serialization; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + internal class ViewParameters + { + public Type Type { get; } + public IEnumerable Properties { get; } + + public ViewParameters(Type type, IEnumerable properties) + { + Type = type; + Properties = properties; + } + } + + internal class PropertyFormat + { + public PropertyInfo Property { get; } + public FormatTableAttribute FormatTable { get; } + + public int? Index { get; } + public string Label { get; } + public int? Width { get; } + public PropertyOrigin? Origin { get; } + + public PropertyFormat(PropertyInfo propertyInfo) + { + Property = propertyInfo; + FormatTable = Property.GetCustomAttributes().FirstOrDefault(); + var origin = Property.GetCustomAttributes().FirstOrDefault(); + + Index = FormatTable?.HasIndex ?? false ? (int?)FormatTable.Index : null; + Label = FormatTable?.Label ?? propertyInfo.Name; + Width = FormatTable?.HasWidth ?? false ? (int?)FormatTable.Width : null; + // If we have an index, we don't want to use Origin. + Origin = FormatTable?.HasIndex ?? false ? null : origin?.Origin; + } + } + + [Serializable] + [XmlRoot(nameof(Configuration))] + public class Configuration + { + [XmlElement("ViewDefinitions")] + public ViewDefinitions ViewDefinitions { get; set; } + } + + [Serializable] + public class ViewDefinitions + { + //https://stackoverflow.com/a/10518657/294804 + [XmlElement("View")] + public List Views { get; set; } + } + + [Serializable] + public class View + { + [XmlElement(nameof(Name))] + public string Name { get; set; } + [XmlElement(nameof(ViewSelectedBy))] + public ViewSelectedBy ViewSelectedBy { get; set; } + [XmlElement(nameof(TableControl))] + public TableControl TableControl { get; set; } + } + + [Serializable] + public class ViewSelectedBy + { + [XmlElement(nameof(TypeName))] + public string TypeName { get; set; } + } + + [Serializable] + public class TableControl + { + [XmlElement(nameof(TableHeaders))] + public TableHeaders TableHeaders { get; set; } + [XmlElement(nameof(TableRowEntries))] + public TableRowEntries TableRowEntries { get; set; } + } + + [Serializable] + public class TableHeaders + { + [XmlElement("TableColumnHeader")] + public List TableColumnHeaders { get; set; } + } + + [Serializable] + public class TableColumnHeader + { + [XmlElement(nameof(Label))] + public string Label { get; set; } + [XmlElement(nameof(Width))] + public int? Width { get; set; } + + //https://stackoverflow.com/a/4095225/294804 + public bool ShouldSerializeWidth() => Width.HasValue; + } + + [Serializable] + public class TableRowEntries + { + [XmlElement(nameof(TableRowEntry))] + public TableRowEntry TableRowEntry { get; set; } + } + + [Serializable] + public class TableRowEntry + { + [XmlElement(nameof(TableColumnItems))] + public TableColumnItems TableColumnItems { get; set; } + } + + [Serializable] + public class TableColumnItems + { + [XmlElement("TableColumnItem")] + public List TableItems { get; set; } + } + + [Serializable] + public class TableColumnItem + { + [XmlElement(nameof(PropertyName))] + public string PropertyName { get; set; } + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs b/src/AppConfiguration/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs new file mode 100644 index 000000000000..5bf54fc727a9 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs @@ -0,0 +1,177 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + internal class HelpMetadataOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public HelpMetadataOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"--- +external help file:{(!String.IsNullOrEmpty(HelpInfo.ExternalHelpFilename) ? $" {HelpInfo.ExternalHelpFilename}" : String.Empty)} +Module Name: {HelpInfo.ModuleName} +online version: {HelpInfo.OnlineVersion} +schema: {HelpInfo.Schema.ToString(3)} +--- + +"; + } + + internal class HelpSyntaxOutput + { + public MarkdownSyntaxHelpInfo SyntaxInfo { get; } + public bool HasMultipleParameterSets { get; } + + public HelpSyntaxOutput(MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) + { + SyntaxInfo = syntaxInfo; + HasMultipleParameterSets = hasMultipleParameterSets; + } + + public override string ToString() + { + var psnText = HasMultipleParameterSets ? $"### {SyntaxInfo.ParameterSetName}{(SyntaxInfo.IsDefault ? " (Default)" : String.Empty)}{Environment.NewLine}" : String.Empty; + return $@"{psnText}``` +{SyntaxInfo.SyntaxText} +``` + +"; + } + } + + internal class HelpExampleOutput + { + public MarkdownExampleHelpInfo ExampleInfo { get; } + + public HelpExampleOutput(MarkdownExampleHelpInfo exampleInfo) + { + ExampleInfo = exampleInfo; + } + + public override string ToString() => $@"{ExampleNameHeader}{ExampleInfo.Name} +{ExampleCodeHeader} +{ExampleInfo.Code} +{ExampleCodeFooter} + +{ExampleInfo.Description.ToDescriptionFormat()} + +"; + } + + + internal class HelpParameterOutput + { + public MarkdownParameterHelpInfo ParameterInfo { get; } + + public HelpParameterOutput(MarkdownParameterHelpInfo parameterInfo) + { + ParameterInfo = parameterInfo; + } + + public override string ToString() + { + var pipelineInputTypes = new[] + { + ParameterInfo.AcceptsPipelineByValue ? "ByValue" : String.Empty, + ParameterInfo.AcceptsPipelineByPropertyName ? "ByPropertyName" : String.Empty + }.JoinIgnoreEmpty(", "); + var pipelineInput = ParameterInfo.AcceptsPipelineByValue || ParameterInfo.AcceptsPipelineByPropertyName + ? $@"{true} ({pipelineInputTypes})" + : false.ToString(); + + return $@"### -{ParameterInfo.Name} +{ParameterInfo.Description.ToDescriptionFormat()} + +```yaml +Type: {ParameterInfo.Type.FullName} +Parameter Sets: {(ParameterInfo.HasAllParameterSets ? "(All)" : ParameterInfo.ParameterSetNames.JoinIgnoreEmpty(", "))} +Aliases:{(ParameterInfo.Aliases.Any() ? $" {ParameterInfo.Aliases.JoinIgnoreEmpty(", ")}" : String.Empty)} + +Required: {ParameterInfo.IsRequired} +Position: {ParameterInfo.Position} +Default value: {ParameterInfo.DefaultValue} +Accept pipeline input: {pipelineInput} +Accept wildcard characters: {ParameterInfo.AcceptsWildcardCharacters} +``` + +"; + } + } + + internal class ModulePageMetadataOutput + { + public PsModuleHelpInfo ModuleInfo { get; } + + private static string HelpLinkPrefix { get; } = @"https://docs.microsoft.com/en-us/powershell/module/"; + + public ModulePageMetadataOutput(PsModuleHelpInfo moduleInfo) + { + ModuleInfo = moduleInfo; + } + + public override string ToString() => $@"--- +Module Name: {ModuleInfo.Name} +Module Guid: {ModuleInfo.Guid} +Download Help Link: {HelpLinkPrefix}{ModuleInfo.Name.ToLowerInvariant()} +Help Version: 1.0.0.0 +Locale: en-US +--- + +"; + } + + internal class ModulePageCmdletOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public ModulePageCmdletOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"### [{HelpInfo.CmdletName}]({HelpInfo.CmdletName}.md) +{HelpInfo.Description.ToDescriptionFormat()} + +"; + } + + internal static class PsHelpOutputExtensions + { + public static string EscapeAngleBrackets(this string text) => text?.Replace("<", @"\<").Replace(">", @"\>"); + public static string ReplaceSentenceEndWithNewline(this string text) => text?.Replace(". ", $".{Environment.NewLine}").Replace(". ", $".{Environment.NewLine}"); + public static string ReplaceBrWithNewline(this string text) => text?.Replace("
", $"{Environment.NewLine}"); + public static string ToDescriptionFormat(this string text, bool escapeAngleBrackets = true) + { + var description = text?.ReplaceBrWithNewline(); + description = escapeAngleBrackets ? description?.EscapeAngleBrackets() : description; + return description?.ReplaceSentenceEndWithNewline().Trim(); + } + + public const string ExampleNameHeader = "### "; + public const string ExampleCodeHeader = "```powershell"; + public const string ExampleCodeFooter = "```"; + + public static HelpMetadataOutput ToHelpMetadataOutput(this MarkdownHelpInfo helpInfo) => new HelpMetadataOutput(helpInfo); + + public static HelpSyntaxOutput ToHelpSyntaxOutput(this MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) => new HelpSyntaxOutput(syntaxInfo, hasMultipleParameterSets); + + public static HelpExampleOutput ToHelpExampleOutput(this MarkdownExampleHelpInfo exampleInfo) => new HelpExampleOutput(exampleInfo); + + public static HelpParameterOutput ToHelpParameterOutput(this MarkdownParameterHelpInfo parameterInfo) => new HelpParameterOutput(parameterInfo); + + public static ModulePageMetadataOutput ToModulePageMetadataOutput(this PsModuleHelpInfo moduleInfo) => new ModulePageMetadataOutput(moduleInfo); + + public static ModulePageCmdletOutput ToModulePageCmdletOutput(this MarkdownHelpInfo helpInfo) => new ModulePageCmdletOutput(helpInfo); + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/Models/PsHelpTypes.cs b/src/AppConfiguration/generated/runtime/BuildTime/Models/PsHelpTypes.cs new file mode 100644 index 000000000000..05d936c747ee --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/Models/PsHelpTypes.cs @@ -0,0 +1,199 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + internal class PsHelpInfo + { + public string CmdletName { get; } + public string ModuleName { get; } + public string Synopsis { get; } + public string Description { get; } + public string AlertText { get; } + public string Category { get; } + public PsHelpLinkInfo OnlineVersion { get; } + public PsHelpLinkInfo[] RelatedLinks { get; } + public bool? HasCommonParameters { get; } + public bool? HasWorkflowCommonParameters { get; } + + public PsHelpTypeInfo[] InputTypes { get; } + public PsHelpTypeInfo[] OutputTypes { get; } + public PsHelpExampleInfo[] Examples { get; set; } + public string[] Aliases { get; } + + public PsParameterHelpInfo[] Parameters { get; } + public PsHelpSyntaxInfo[] Syntax { get; } + + public object Component { get; } + public object Functionality { get; } + public object PsSnapIn { get; } + public object Role { get; } + public string NonTerminatingErrors { get; } + + public PsHelpInfo(PSObject helpObject = null) + { + helpObject = helpObject ?? new PSObject(); + CmdletName = helpObject.GetProperty("Name").NullIfEmpty() ?? helpObject.GetNestedProperty("details", "name"); + ModuleName = helpObject.GetProperty("ModuleName"); + Synopsis = helpObject.GetProperty("Synopsis"); + Description = helpObject.GetProperty("description").EmptyIfNull().ToDescriptionText().NullIfEmpty() ?? + helpObject.GetNestedProperty("details", "description").EmptyIfNull().ToDescriptionText(); + AlertText = helpObject.GetNestedProperty("alertSet", "alert").EmptyIfNull().ToDescriptionText(); + Category = helpObject.GetProperty("Category"); + HasCommonParameters = helpObject.GetProperty("CommonParameters").ToNullableBool(); + HasWorkflowCommonParameters = helpObject.GetProperty("WorkflowCommonParameters").ToNullableBool(); + + var links = helpObject.GetNestedProperty("relatedLinks", "navigationLink").EmptyIfNull().Select(nl => nl.ToLinkInfo()).ToArray(); + OnlineVersion = links.FirstOrDefault(l => l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length == 1); + RelatedLinks = links.Where(l => !l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length != 1).ToArray(); + + InputTypes = helpObject.GetNestedProperty("inputTypes", "inputType").EmptyIfNull().Select(it => it.ToTypeInfo()).ToArray(); + OutputTypes = helpObject.GetNestedProperty("returnValues", "returnValue").EmptyIfNull().Select(rv => rv.ToTypeInfo()).ToArray(); + Examples = helpObject.GetNestedProperty("examples", "example").EmptyIfNull().Select(e => e.ToExampleInfo()).ToArray(); + Aliases = helpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); + + Parameters = helpObject.GetNestedProperty("parameters", "parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + Syntax = helpObject.GetNestedProperty("syntax", "syntaxItem").EmptyIfNull().Select(si => si.ToSyntaxInfo()).ToArray(); + + Component = helpObject.GetProperty("Component"); + Functionality = helpObject.GetProperty("Functionality"); + PsSnapIn = helpObject.GetProperty("PSSnapIn"); + Role = helpObject.GetProperty("Role"); + NonTerminatingErrors = helpObject.GetProperty("nonTerminatingErrors"); + } + } + + internal class PsHelpTypeInfo + { + public string Name { get; } + public string Description { get; } + + public PsHelpTypeInfo(PSObject typeObject) + { + Name = typeObject.GetNestedProperty("type", "name").EmptyIfNull().Trim(); + Description = typeObject.GetProperty("description").EmptyIfNull().ToDescriptionText(); + } + } + + internal class PsHelpLinkInfo + { + public string Uri { get; } + public string Text { get; } + + public PsHelpLinkInfo(PSObject linkObject) + { + Uri = linkObject.GetProperty("uri"); + Text = linkObject.GetProperty("linkText"); + } + } + + internal class PsHelpSyntaxInfo + { + public string CmdletName { get; } + public PsParameterHelpInfo[] Parameters { get; } + + public PsHelpSyntaxInfo(PSObject syntaxObject) + { + CmdletName = syntaxObject.GetProperty("name"); + Parameters = syntaxObject.GetProperty("parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + } + } + + internal class PsHelpExampleInfo + { + public string Title { get; } + public string Code { get; } + public string Remarks { get; } + + public PsHelpExampleInfo(PSObject exampleObject) + { + Title = exampleObject.GetProperty("title"); + Code = exampleObject.GetProperty("code"); + Remarks = exampleObject.GetProperty("remarks").EmptyIfNull().ToDescriptionText(); + } + public PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) + { + Title = markdownExample.Name; + Code = markdownExample.Code; + Remarks = markdownExample.Description; + } + + public static implicit operator PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) => new PsHelpExampleInfo(markdownExample); + } + + internal class PsParameterHelpInfo + { + public string DefaultValueAsString { get; } + + public string Name { get; } + public string TypeName { get; } + public string Description { get; } + public string SupportsPipelineInput { get; } + public string PositionText { get; } + public string[] ParameterSetNames { get; } + public string[] Aliases { get; } + + public bool? SupportsGlobbing { get; } + public bool? IsRequired { get; } + public bool? IsVariableLength { get; } + public bool? IsDynamic { get; } + + public PsParameterHelpInfo(PSObject parameterHelpObject = null) + { + parameterHelpObject = parameterHelpObject ?? new PSObject(); + DefaultValueAsString = parameterHelpObject.GetProperty("defaultValue"); + Name = parameterHelpObject.GetProperty("name"); + TypeName = parameterHelpObject.GetProperty("parameterValue").NullIfEmpty() ?? parameterHelpObject.GetNestedProperty("type", "name"); + Description = parameterHelpObject.GetProperty("Description").EmptyIfNull().ToDescriptionText(); + SupportsPipelineInput = parameterHelpObject.GetProperty("pipelineInput"); + PositionText = parameterHelpObject.GetProperty("position"); + ParameterSetNames = parameterHelpObject.GetProperty("parameterSetName").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + Aliases = parameterHelpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + + SupportsGlobbing = parameterHelpObject.GetProperty("globbing").ToNullableBool(); + IsRequired = parameterHelpObject.GetProperty("required").ToNullableBool(); + IsVariableLength = parameterHelpObject.GetProperty("variableLength").ToNullableBool(); + IsDynamic = parameterHelpObject.GetProperty("isDynamic").ToNullableBool(); + } + } + + internal class PsModuleHelpInfo + { + public string Name { get; } + public Guid Guid { get; } + public string Description { get; } + + public PsModuleHelpInfo(PSModuleInfo moduleInfo) + : this(moduleInfo?.Name ?? String.Empty, moduleInfo?.Guid ?? Guid.NewGuid(), moduleInfo?.Description ?? String.Empty) + { + } + + public PsModuleHelpInfo(string name, Guid guid, string description) + { + Name = name; + Guid = guid; + Description = description; + } + } + + internal static class HelpTypesExtensions + { + public static PsHelpInfo ToPsHelpInfo(this PSObject helpObject) => new PsHelpInfo(helpObject); + public static PsParameterHelpInfo ToPsParameterHelpInfo(this PSObject parameterHelpObject) => new PsParameterHelpInfo(parameterHelpObject); + + public static string ToDescriptionText(this IEnumerable descriptionObject) => descriptionObject != null + ? String.Join(Environment.NewLine, descriptionObject.Select(dl => dl.GetProperty("Text").EmptyIfNull())).NullIfWhiteSpace() + : null; + public static PsHelpTypeInfo ToTypeInfo(this PSObject typeObject) => new PsHelpTypeInfo(typeObject); + public static PsHelpExampleInfo ToExampleInfo(this PSObject exampleObject) => new PsHelpExampleInfo(exampleObject); + public static PsHelpLinkInfo ToLinkInfo(this PSObject linkObject) => new PsHelpLinkInfo(linkObject); + public static PsHelpSyntaxInfo ToSyntaxInfo(this PSObject syntaxObject) => new PsHelpSyntaxInfo(syntaxObject); + public static PsModuleHelpInfo ToModuleInfo(this PSModuleInfo moduleInfo) => new PsModuleHelpInfo(moduleInfo); + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs b/src/AppConfiguration/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs new file mode 100644 index 000000000000..450419dc84fe --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs @@ -0,0 +1,291 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + internal class MarkdownHelpInfo + { + public string ExternalHelpFilename { get; } + public string ModuleName { get; } + public string OnlineVersion { get; } + public Version Schema { get; } + + public string CmdletName { get; } + public string[] Aliases { get; } + public string Synopsis { get; } + public string Description { get; } + + public MarkdownSyntaxHelpInfo[] SyntaxInfos { get; } + public MarkdownExampleHelpInfo[] Examples { get; } + public MarkdownParameterHelpInfo[] Parameters { get; } + + public string[] Inputs { get; } + public string[] Outputs { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + public string[] RelatedLinks { get; } + + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public MarkdownHelpInfo(VariantGroup variantGroup, string examplesFolder, string externalHelpFilename = "") + { + ExternalHelpFilename = externalHelpFilename; + ModuleName = variantGroup.ModuleName; + var helpInfo = variantGroup.HelpInfo; + var commentInfo = variantGroup.CommentInfo; + Schema = Version.Parse("2.0.0"); + + CmdletName = variantGroup.CmdletName; + Aliases = (variantGroup.Aliases.NullIfEmpty() ?? helpInfo.Aliases).Where(a => a != "None").ToArray(); + Synopsis = commentInfo.Synopsis; + Description = commentInfo.Description; + + SyntaxInfos = variantGroup.Variants + .Select(v => new MarkdownSyntaxHelpInfo(v, variantGroup.ParameterGroups, v.VariantName == variantGroup.DefaultParameterSetName)) + .OrderByDescending(v => v.IsDefault).ThenBy(v => v.ParameterSetName).ToArray(); + Examples = GetExamplesFromMarkdown(examplesFolder).NullIfEmpty() + ?? helpInfo.Examples.Select(e => e.ToExampleHelpInfo()).ToArray().NullIfEmpty() + ?? DefaultExampleHelpInfos; + + Parameters = variantGroup.ParameterGroups + .Where(pg => !pg.DontShow) + .Select(pg => new MarkdownParameterHelpInfo( + variantGroup.Variants.SelectMany(v => v.HelpInfo.Parameters).Where(phi => phi.Name == pg.ParameterName).ToArray(), pg)) + .OrderBy(phi => phi.Name).ToArray(); + + Inputs = commentInfo.Inputs; + Outputs = commentInfo.Outputs; + + ComplexInterfaceInfos = variantGroup.ComplexInterfaceInfos; + OnlineVersion = commentInfo.OnlineVersion; + RelatedLinks = commentInfo.RelatedLinks; + + SupportsShouldProcess = variantGroup.SupportsShouldProcess; + SupportsPaging = variantGroup.SupportsPaging; + } + + private MarkdownExampleHelpInfo[] GetExamplesFromMarkdown(string examplesFolder) + { + var filePath = Path.Combine(examplesFolder, $"{CmdletName}.md"); + if (!Directory.Exists(examplesFolder) || !File.Exists(filePath)) return null; + + var lines = File.ReadAllLines(filePath); + var nameIndices = lines.Select((l, i) => l.StartsWith(ExampleNameHeader) ? i : -1).Where(i => i != -1).ToArray(); + //https://codereview.stackexchange.com/a/187148/68772 + var indexCountGroups = nameIndices.Skip(1).Append(lines.Length).Zip(nameIndices, (next, current) => (NameIndex: current, LineCount: next - current)); + var exampleGroups = indexCountGroups.Select(icg => lines.Skip(icg.NameIndex).Take(icg.LineCount).ToArray()); + return exampleGroups.Select(eg => + { + var name = eg.First().Replace(ExampleNameHeader, String.Empty); + var codeStartIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeHeader) ? (int?)i : null).FirstOrDefault(i => i.HasValue); + var codeEndIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeFooter) ? (int?)i : null).FirstOrDefault(i => i.HasValue && i != codeStartIndex); + var code = codeStartIndex.HasValue && codeEndIndex.HasValue + ? String.Join(Environment.NewLine, eg.Skip(codeStartIndex.Value + 1).Take(codeEndIndex.Value - (codeStartIndex.Value + 1))) + : String.Empty; + var descriptionStartIndex = (codeEndIndex ?? 0) + 1; + descriptionStartIndex = String.IsNullOrWhiteSpace(eg[descriptionStartIndex]) ? descriptionStartIndex + 1 : descriptionStartIndex; + var descriptionEndIndex = eg.Length - 1; + descriptionEndIndex = String.IsNullOrWhiteSpace(eg[descriptionEndIndex]) ? descriptionEndIndex - 1 : descriptionEndIndex; + var description = String.Join(Environment.NewLine, eg.Skip(descriptionStartIndex).Take((descriptionEndIndex + 1) - descriptionStartIndex)); + return new MarkdownExampleHelpInfo(name, code, description); + }).ToArray(); + } + } + + internal class MarkdownSyntaxHelpInfo + { + public Variant Variant { get; } + public bool IsDefault { get; } + public string ParameterSetName { get; } + public Parameter[] Parameters { get; } + public string SyntaxText { get; } + + public MarkdownSyntaxHelpInfo(Variant variant, ParameterGroup[] parameterGroups, bool isDefault) + { + Variant = variant; + IsDefault = isDefault; + ParameterSetName = Variant.VariantName; + Parameters = Variant.Parameters + .Where(p => !p.DontShow).OrderByDescending(p => p.IsMandatory) + //https://stackoverflow.com/a/6461526/294804 + .ThenByDescending(p => p.Position.HasValue).ThenBy(p => p.Position) + // Use the OrderCategory of the parameter group because the final order category is the highest of the group, and not the order category of the individual parameters from the variants. + .ThenBy(p => parameterGroups.First(pg => pg.ParameterName == p.ParameterName).OrderCategory).ThenBy(p => p.ParameterName).ToArray(); + SyntaxText = CreateSyntaxFormat(); + } + + //https://github.com/PowerShell/platyPS/blob/a607a926bfffe1e1a1e53c19e0057eddd0c07611/src/Markdown.MAML/Renderer/Markdownv2Renderer.cs#L29-L32 + private const int SyntaxLineWidth = 110; + private string CreateSyntaxFormat() + { + var parameterStrings = Parameters.Select(p => p.ToPropertySyntaxOutput().ToString()); + if (Variant.SupportsShouldProcess) + { + parameterStrings = parameterStrings.Append(" [-Confirm]").Append(" [-WhatIf]"); + } + if (Variant.SupportsPaging) + { + parameterStrings = parameterStrings.Append(" [-First ]").Append(" [-IncludeTotalCount]").Append(" [-Skip ]"); + } + parameterStrings = parameterStrings.Append(" []"); + + var lines = new List(20); + return parameterStrings.Aggregate(Variant.CmdletName, (current, ps) => + { + var combined = current + ps; + if (combined.Length <= SyntaxLineWidth) return combined; + + lines.Add(current); + return ps; + }, last => + { + lines.Add(last); + return String.Join(Environment.NewLine, lines); + }); + } + } + + internal class MarkdownExampleHelpInfo + { + public string Name { get; } + public string Code { get; } + public string Description { get; } + + public MarkdownExampleHelpInfo(string name, string code, string description) + { + Name = name; + Code = code; + Description = description; + } + } + + internal class MarkdownParameterHelpInfo + { + public string Name { get; set; } + public string Description { get; set; } + public Type Type { get; set; } + public string Position { get; set; } + public string DefaultValue { get; set; } + + public bool HasAllParameterSets { get; set; } + public string[] ParameterSetNames { get; set; } + public string[] Aliases { get; set; } + + public bool IsRequired { get; set; } + public bool IsDynamic { get; set; } + public bool AcceptsPipelineByValue { get; set; } + public bool AcceptsPipelineByPropertyName { get; set; } + public bool AcceptsWildcardCharacters { get; set; } + + // For use by common parameters that have no backing data in the objects themselves. + public MarkdownParameterHelpInfo() { } + + public MarkdownParameterHelpInfo(PsParameterHelpInfo[] parameterHelpInfos, ParameterGroup parameterGroup) + { + Name = parameterGroup.ParameterName; + Description = parameterGroup.Description.NullIfEmpty() + ?? parameterHelpInfos.Select(phi => phi.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + Type = parameterGroup.ParameterType; + Position = parameterGroup.FirstPosition?.ToString() + ?? parameterHelpInfos.Select(phi => phi.PositionText).FirstOrDefault(d => !String.IsNullOrEmpty(d)).ToUpperFirstCharacter().NullIfEmpty() + ?? "Named"; + // This no longer uses firstHelpInfo.DefaultValueAsString since it seems to be broken. For example, it has a value of 0 for Int32, but no default value was declared. + DefaultValue = parameterGroup.DefaultInfo?.Script ?? "None"; + + HasAllParameterSets = parameterGroup.HasAllVariants; + ParameterSetNames = (parameterGroup.Parameters.Select(p => p.VariantName).ToArray().NullIfEmpty() + ?? parameterHelpInfos.SelectMany(phi => phi.ParameterSetNames).Distinct()) + .OrderBy(psn => psn).ToArray(); + Aliases = parameterGroup.Aliases.NullIfEmpty() ?? parameterHelpInfos.SelectMany(phi => phi.Aliases).ToArray(); + + IsRequired = parameterHelpInfos.Select(phi => phi.IsRequired).FirstOrDefault(r => r == true) ?? parameterGroup.Parameters.Any(p => p.IsMandatory); + IsDynamic = parameterHelpInfos.Select(phi => phi.IsDynamic).FirstOrDefault(d => d == true) ?? false; + AcceptsPipelineByValue = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByValue")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipeline; + AcceptsPipelineByPropertyName = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByPropertyName")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipelineByPropertyName; + AcceptsWildcardCharacters = parameterGroup.SupportsWildcards; + } + } + + internal static class MarkdownTypesExtensions + { + public static MarkdownExampleHelpInfo ToExampleHelpInfo(this PsHelpExampleInfo exampleInfo) => new MarkdownExampleHelpInfo(exampleInfo.Title, exampleInfo.Code, exampleInfo.Remarks); + + public static MarkdownExampleHelpInfo[] DefaultExampleHelpInfos = + { + new MarkdownExampleHelpInfo("Example 1: {{ Add title here }}", $@"PS C:\> {{{{ Add code here }}}}{Environment.NewLine}{Environment.NewLine}{{{{ Add output here }}}}", @"{{ Add description here }}"), + new MarkdownExampleHelpInfo("Example 2: {{ Add title here }}", $@"PS C:\> {{{{ Add code here }}}}{Environment.NewLine}{Environment.NewLine}{{{{ Add output here }}}}", @"{{ Add description here }}") + }; + + public static MarkdownParameterHelpInfo[] SupportsShouldProcessParameters = + { + new MarkdownParameterHelpInfo + { + Name = "Confirm", + Description ="Prompts you for confirmation before running the cmdlet.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "cf" } + }, + new MarkdownParameterHelpInfo + { + Name = "WhatIf", + Description ="Shows what would happen if the cmdlet runs. The cmdlet is not run.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "wi" } + } + }; + + public static MarkdownParameterHelpInfo[] SupportsPagingParameters = + { + new MarkdownParameterHelpInfo + { + Name = "First", + Description ="Gets only the first 'n' objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "IncludeTotalCount", + Description ="Reports the number of objects in the data set (an integer) followed by the objects. If the cmdlet cannot determine the total count, it returns \"Unknown total count\".", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "Skip", + Description ="Ignores the first 'n' objects and then gets the remaining objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + } + }; + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/Models/PsProxyOutputs.cs b/src/AppConfiguration/generated/runtime/BuildTime/Models/PsProxyOutputs.cs new file mode 100644 index 000000000000..cdbe4b089949 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/Models/PsProxyOutputs.cs @@ -0,0 +1,513 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + internal class OutputTypeOutput + { + public PSTypeName[] OutputTypes { get; } + + public OutputTypeOutput(IEnumerable outputTypes) + { + OutputTypes = outputTypes.ToArray(); + } + + public override string ToString() => OutputTypes != null && OutputTypes.Any() ? $"[OutputType({OutputTypes.Select(ot => $"[{ot}]").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class CmdletBindingOutput + { + public VariantGroup VariantGroup { get; } + + public CmdletBindingOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + + public override string ToString() + { + var dpsText = VariantGroup.DefaultParameterSetName.IsValidDefaultParameterSetName() ? $"DefaultParameterSetName='{VariantGroup.DefaultParameterSetName}'" : String.Empty; + var sspText = VariantGroup.SupportsShouldProcess ? $"SupportsShouldProcess{ItemSeparator}ConfirmImpact='Medium'" : String.Empty; + var pbText = $"PositionalBinding={false.ToPsBool()}"; + var propertyText = new[] { dpsText, pbText, sspText }.JoinIgnoreEmpty(ItemSeparator); + return $"[CmdletBinding({propertyText})]{Environment.NewLine}"; + } + } + + internal class ParameterOutput + { + public Parameter Parameter { get; } + public bool HasMultipleVariantsInVariantGroup { get; } + public bool HasAllVariantsInParameterGroup { get; } + + public ParameterOutput(Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) + { + Parameter = parameter; + HasMultipleVariantsInVariantGroup = hasMultipleVariantsInVariantGroup; + HasAllVariantsInParameterGroup = hasAllVariantsInParameterGroup; + } + + public override string ToString() + { + var psnText = HasMultipleVariantsInVariantGroup && !HasAllVariantsInParameterGroup ? $"ParameterSetName='{Parameter.VariantName}'" : String.Empty; + var positionText = Parameter.Position != null ? $"Position={Parameter.Position}" : String.Empty; + var mandatoryText = Parameter.IsMandatory ? "Mandatory" : String.Empty; + var dontShowText = Parameter.DontShow ? "DontShow" : String.Empty; + var vfpText = Parameter.ValueFromPipeline ? "ValueFromPipeline" : String.Empty; + var vfpbpnText = Parameter.ValueFromPipelineByPropertyName ? "ValueFromPipelineByPropertyName" : String.Empty; + var propertyText = new[] { psnText, positionText, mandatoryText, dontShowText, vfpText, vfpbpnText }.JoinIgnoreEmpty(ItemSeparator); + return $"{Indent}[Parameter({propertyText})]{Environment.NewLine}"; + } + } + + internal class AliasOutput + { + public string[] Aliases { get; } + public bool IncludeIndent { get; } + + public AliasOutput(string[] aliases, bool includeIndent = false) + { + Aliases = aliases; + IncludeIndent = includeIndent; + } + + public override string ToString() => Aliases?.Any() ?? false ? $"{(IncludeIndent ? Indent : String.Empty)}[Alias({Aliases.Select(an => $"'{an}'").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class ValidateNotNullOutput + { + public bool HasValidateNotNull { get; } + + public ValidateNotNullOutput(bool hasValidateNotNull) + { + HasValidateNotNull = hasValidateNotNull; + } + + public override string ToString() => HasValidateNotNull ? $"{Indent}[ValidateNotNull()]{Environment.NewLine}" : String.Empty; + } + + internal class ArgumentCompleterOutput + { + public CompleterInfo CompleterInfo { get; } + + public ArgumentCompleterOutput(CompleterInfo completerInfo) + { + CompleterInfo = completerInfo; + } + + public override string ToString() => CompleterInfo != null + ? $"{Indent}[ArgumentCompleter({(CompleterInfo.IsTypeCompleter ? $"[{CompleterInfo.Type.Unwrap().ToPsType()}]" : $"{{{CompleterInfo.Script.ToPsSingleLine("; ")}}}")})]{Environment.NewLine}" + : String.Empty; + } + + internal class DefaultInfoOutput + { + public bool HasDefaultInfo { get; } + public DefaultInfo DefaultInfo { get; } + + public DefaultInfoOutput(ParameterGroup parameterGroup) + { + HasDefaultInfo = parameterGroup.HasDefaultInfo; + DefaultInfo = parameterGroup.DefaultInfo; + } + + public override string ToString() + { + var nameText = !String.IsNullOrEmpty(DefaultInfo?.Name) ? $"Name='{DefaultInfo?.Name}'" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(DefaultInfo?.Description) ? $"Description='{DefaultInfo?.Description.ToPsStringLiteral()}'" : String.Empty; + var scriptText = !String.IsNullOrEmpty(DefaultInfo?.Script) ? $"Script='{DefaultInfo?.Script.ToPsSingleLine("; ")}'" : String.Empty; + var propertyText = new[] { nameText, descriptionText, scriptText }.JoinIgnoreEmpty(ItemSeparator); + return HasDefaultInfo ? $"{Indent}[{typeof(DefaultInfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class ParameterTypeOutput + { + public Type ParameterType { get; } + + public ParameterTypeOutput(Type parameterType) + { + ParameterType = parameterType; + } + + public override string ToString() => $"{Indent}[{ParameterType.ToPsType()}]{Environment.NewLine}"; + } + + internal class ParameterNameOutput + { + public string ParameterName { get; } + public bool IsLast { get; } + + public ParameterNameOutput(string parameterName, bool isLast) + { + ParameterName = parameterName; + IsLast = isLast; + } + + public override string ToString() => $"{Indent}${{{ParameterName}}}{(IsLast ? String.Empty : $",{Environment.NewLine}")}{Environment.NewLine}"; + } + + internal class BeginOutput + { + public VariantGroup VariantGroup { get; } + + public BeginOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + + public override string ToString() => $@"begin {{ +{Indent}try {{ +{Indent}{Indent}$outBuffer = $null +{Indent}{Indent}if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {{ +{Indent}{Indent}{Indent}$PSBoundParameters['OutBuffer'] = 1 +{Indent}{Indent}}} +{Indent}{Indent}$parameterSet = $PSCmdlet.ParameterSetName +{GetParameterSetToCmdletMapping()}{GetDefaultValuesStatements()} +{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) +{Indent}{Indent}$scriptCmd = {{& $wrappedCmd @PSBoundParameters}} +{Indent}{Indent}$steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) +{Indent}{Indent}$steppablePipeline.Begin($PSCmdlet) +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} + +"; + + private string GetParameterSetToCmdletMapping() + { + var sb = new StringBuilder(); + sb.AppendLine($"{Indent}{Indent}$mapping = @{{"); + foreach (var variant in VariantGroup.Variants) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}{variant.VariantName} = '{variant.PrivateModuleName}\{variant.PrivateCmdletName}';"); + } + sb.Append($"{Indent}{Indent}}}"); + return sb.ToString(); + } + + private string GetDefaultValuesStatements() + { + var defaultInfos = VariantGroup.ParameterGroups.Where(pg => pg.HasDefaultInfo).Select(pg => pg.DefaultInfo).ToArray(); + var sb = new StringBuilder(); + + foreach (var defaultInfo in defaultInfos) + { + var variantListString = defaultInfo.ParameterGroup.VariantNames.ToPsList(); + var parameterName = defaultInfo.ParameterGroup.ParameterName; + sb.AppendLine(); + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}')) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.Append($"{Indent}{Indent}}}"); + } + return sb.ToString(); + } + } + + internal class ProcessOutput + { + public override string ToString() => $@"process {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.Process($_) +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} + +"; + } + + internal class EndOutput + { + public override string ToString() => $@"end {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.End() +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} +"; + } + + internal class HelpCommentOutput + { + public VariantGroup VariantGroup { get; } + public CommentInfo CommentInfo { get; } + + public HelpCommentOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + CommentInfo = variantGroup.CommentInfo; + } + + public override string ToString() + { + var inputs = String.Join(Environment.NewLine, CommentInfo.Inputs.Select(i => $".Inputs{Environment.NewLine}{i}")); + var inputsText = !String.IsNullOrEmpty(inputs) ? $"{Environment.NewLine}{inputs}" : String.Empty; + var outputs = String.Join(Environment.NewLine, CommentInfo.Outputs.Select(o => $".Outputs{Environment.NewLine}{o}")); + var outputsText = !String.IsNullOrEmpty(outputs) ? $"{Environment.NewLine}{outputs}" : String.Empty; + var notes = String.Join($"{Environment.NewLine}{Environment.NewLine}", VariantGroup.ComplexInterfaceInfos.Select(cii => cii.ToNoteOutput())); + var notesText = !String.IsNullOrEmpty(notes) ? $"{Environment.NewLine}.Notes{Environment.NewLine}{ComplexParameterHeader}{notes}" : String.Empty; + var relatedLinks = String.Join(Environment.NewLine, CommentInfo.RelatedLinks.Select(l => $".Link{Environment.NewLine}{l}")); + var relatedLinksText = !String.IsNullOrEmpty(relatedLinks) ? $"{Environment.NewLine}{relatedLinks}" : String.Empty; + var examples = ""; + foreach (var example in VariantGroup.HelpInfo.Examples) + { + examples = examples + ".Example" + "\r\n" + example.Code + "\r\n"; + } + return $@"<# +.Synopsis +{CommentInfo.Synopsis.ToDescriptionFormat(false)} +.Description +{CommentInfo.Description.ToDescriptionFormat(false)} +{examples}{inputsText}{outputsText}{notesText} +.Link +{CommentInfo.OnlineVersion}{relatedLinksText} +#> +"; + } + } + + internal class ParameterDescriptionOutput + { + public string Description { get; } + + public ParameterDescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) + ? Description.ToDescriptionFormat(false).NormalizeNewLines() + .Split(new [] { Environment.NewLine }, StringSplitOptions.None) + .Aggregate(String.Empty, (c, n) => c + $"{Indent}# {n}{Environment.NewLine}") + : String.Empty; + } + + internal class ProfileOutput + { + public string ProfileName { get; } + + public ProfileOutput(string profileName) + { + ProfileName = profileName; + } + + public override string ToString() => ProfileName != NoProfiles ? $"[{typeof(ProfileAttribute).ToPsAttributeType()}('{ProfileName}')]{Environment.NewLine}" : String.Empty; + } + + internal class DescriptionOutput + { + public string Description { get; } + + public DescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) ? $"[{typeof(DescriptionAttribute).ToPsAttributeType()}('{Description.ToPsStringLiteral()}')]{Environment.NewLine}" : String.Empty; + } + + internal class ParameterCategoryOutput + { + public ParameterCategory Category { get; } + + public ParameterCategoryOutput(ParameterCategory category) + { + Category = category; + } + + public override string ToString() => $"{Indent}[{typeof(CategoryAttribute).ToPsAttributeType()}('{Category}')]{Environment.NewLine}"; + } + + internal class InfoOutput + { + public InfoAttribute Info { get; } + public Type ParameterType { get; } + + public InfoOutput(InfoAttribute info, Type parameterType) + { + Info = info; + ParameterType = parameterType; + } + + public override string ToString() + { + // Rendering of InfoAttribute members that are not used currently + /*var serializedNameText = Info.SerializedName != null ? $"SerializedName='{Info.SerializedName}'" : String.Empty; + var readOnlyText = Info.ReadOnly ? "ReadOnly" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(Info.Description) ? $"Description='{Info.Description.ToPsStringLiteral()}'" : String.Empty;*/ + + var requiredText = Info.Required ? "Required" : String.Empty; + var unwrappedType = ParameterType.Unwrap(); + var hasValidPossibleTypes = Info.PossibleTypes.Any(pt => pt != unwrappedType); + var possibleTypesText = hasValidPossibleTypes + ? $"PossibleTypes=({Info.PossibleTypes.Select(pt => $"[{pt.ToPsType()}]").JoinIgnoreEmpty(ItemSeparator)})" + : String.Empty; + var propertyText = new[] { /*serializedNameText, */requiredText,/* readOnlyText,*/ possibleTypesText/*, descriptionText*/ }.JoinIgnoreEmpty(ItemSeparator); + return hasValidPossibleTypes ? $"{Indent}[{typeof(InfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class PropertySyntaxOutput + { + public string ParameterName { get; } + public Type ParameterType { get; } + public bool IsMandatory { get; } + public int? Position { get; } + + public bool IncludeSpace { get; } + public bool IncludeDash { get; } + + public PropertySyntaxOutput(Parameter parameter) + { + ParameterName = parameter.ParameterName; + ParameterType = parameter.ParameterType; + IsMandatory = parameter.IsMandatory; + Position = parameter.Position; + IncludeSpace = true; + IncludeDash = true; + } + + public PropertySyntaxOutput(ComplexInterfaceInfo complexInterfaceInfo) + { + ParameterName = complexInterfaceInfo.Name; + ParameterType = complexInterfaceInfo.Type; + IsMandatory = complexInterfaceInfo.Required; + Position = null; + IncludeSpace = false; + IncludeDash = false; + } + + public override string ToString() + { + var leftOptional = !IsMandatory ? "[" : String.Empty; + var leftPositional = Position != null ? "[" : String.Empty; + var rightPositional = Position != null ? "]" : String.Empty; + var type = ParameterType != typeof(SwitchParameter) ? $" <{ParameterType.ToSyntaxTypeName()}>" : String.Empty; + var rightOptional = !IsMandatory ? "]" : String.Empty; + var space = IncludeSpace ? " " : String.Empty; + var dash = IncludeDash ? "-" : String.Empty; + return $"{space}{leftOptional}{leftPositional}{dash}{ParameterName}{rightPositional}{type}{rightOptional}"; + } + } + + internal static class PsProxyOutputExtensions + { + public const string NoParameters = "__NoParameters"; + + public const string AllParameterSets = "__AllParameterSets"; + + public const string HalfIndent = " "; + + public const string Indent = HalfIndent + HalfIndent; + + public const string ItemSeparator = ", "; + + public static readonly string ComplexParameterHeader = $"COMPLEX PARAMETER PROPERTIES{Environment.NewLine}To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables.{Environment.NewLine}{Environment.NewLine}"; + + public static string ToPsBool(this bool value) => $"${value.ToString().ToLowerInvariant()}"; + + public static string ToPsType(this Type type) + { + var regex = new Regex(@"^(.*)`{1}\d+(.*)$"); + var typeText = type.ToString(); + var match = regex.Match(typeText); + return match.Success ? $"{match.Groups[1]}{match.Groups[2]}" : typeText; + } + + public static string ToPsAttributeType(this Type type) => type.ToPsType().RemoveEnd("Attribute"); + + // https://stackoverflow.com/a/5284606/294804 + private static string RemoveEnd(this string text, string suffix) => text.EndsWith(suffix) ? text.Substring(0, text.Length - suffix.Length) : text; + + public static string ToPsSingleLine(this string value, string replacer = " ") => value.ReplaceNewLines(replacer, new []{"
", "\r\n", "\n"}); + + public static string ToPsStringLiteral(this string value) => value?.Replace("'", "''").Replace("‘", "''").Replace("’", "''").ToPsSingleLine().Trim() ?? String.Empty; + + public static string JoinIgnoreEmpty(this IEnumerable values, string separator) => String.Join(separator, values?.Where(v => !String.IsNullOrEmpty(v))); + + // https://stackoverflow.com/a/41961738/294804 + public static string ToSyntaxTypeName(this Type type) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + return $"{type.GetGenericArguments().First().ToSyntaxTypeName()}?"; + } + + if (type.IsGenericType) + { + var genericTypes = String.Join(ItemSeparator, type.GetGenericArguments().Select(ToSyntaxTypeName)); + return $"{type.Name.Split('`').First()}<{genericTypes}>"; + } + + return type.Name; + } + + public static OutputTypeOutput ToOutputTypeOutput(this IEnumerable outputTypes) => new OutputTypeOutput(outputTypes); + + public static CmdletBindingOutput ToCmdletBindingOutput(this VariantGroup variantGroup) => new CmdletBindingOutput(variantGroup); + + public static ParameterOutput ToParameterOutput(this Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) => new ParameterOutput(parameter, hasMultipleVariantsInVariantGroup, hasAllVariantsInParameterGroup); + + public static AliasOutput ToAliasOutput(this string[] aliases, bool includeIndent = false) => new AliasOutput(aliases, includeIndent); + + public static ValidateNotNullOutput ToValidateNotNullOutput(this bool hasValidateNotNull) => new ValidateNotNullOutput(hasValidateNotNull); + + public static ArgumentCompleterOutput ToArgumentCompleterOutput(this CompleterInfo completerInfo) => new ArgumentCompleterOutput(completerInfo); + + public static DefaultInfoOutput ToDefaultInfoOutput(this ParameterGroup parameterGroup) => new DefaultInfoOutput(parameterGroup); + + public static ParameterTypeOutput ToParameterTypeOutput(this Type parameterType) => new ParameterTypeOutput(parameterType); + + public static ParameterNameOutput ToParameterNameOutput(this string parameterName, bool isLast) => new ParameterNameOutput(parameterName, isLast); + + public static BeginOutput ToBeginOutput(this VariantGroup variantGroup) => new BeginOutput(variantGroup); + + public static ProcessOutput ToProcessOutput(this VariantGroup variantGroup) => new ProcessOutput(); + + public static EndOutput ToEndOutput(this VariantGroup variantGroup) => new EndOutput(); + + public static HelpCommentOutput ToHelpCommentOutput(this VariantGroup variantGroup) => new HelpCommentOutput(variantGroup); + + public static ParameterDescriptionOutput ToParameterDescriptionOutput(this string description) => new ParameterDescriptionOutput(description); + + public static ProfileOutput ToProfileOutput(this string profileName) => new ProfileOutput(profileName); + + public static DescriptionOutput ToDescriptionOutput(this string description) => new DescriptionOutput(description); + + public static ParameterCategoryOutput ToParameterCategoryOutput(this ParameterCategory category) => new ParameterCategoryOutput(category); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this Parameter parameter) => new PropertySyntaxOutput(parameter); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this ComplexInterfaceInfo complexInterfaceInfo) => new PropertySyntaxOutput(complexInterfaceInfo); + + public static InfoOutput ToInfoOutput(this InfoAttribute info, Type parameterType) => new InfoOutput(info, parameterType); + + public static string ToNoteOutput(this ComplexInterfaceInfo complexInterfaceInfo, string currentIndent = "", bool includeDashes = false, bool includeBackticks = false, bool isFirst = true) + { + string RenderProperty(ComplexInterfaceInfo info, string indent, bool dash, bool backtick) => + $"{indent}{(dash ? "- " : String.Empty)}{(backtick ? "`" : String.Empty)}{info.ToPropertySyntaxOutput()}{(backtick ? "`" : String.Empty)}: {info.Description}"; + + var nested = complexInterfaceInfo.NestedInfos.Select(ni => + { + var nestedIndent = $"{currentIndent}{HalfIndent}"; + return ni.IsComplexInterface + ? ni.ToNoteOutput(nestedIndent, includeDashes, includeBackticks, false) + : RenderProperty(ni, nestedIndent, includeDashes, includeBackticks); + }).Prepend(RenderProperty(complexInterfaceInfo, currentIndent, !isFirst && includeDashes, !isFirst && includeBackticks)); + return String.Join(Environment.NewLine, nested); + } + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/Models/PsProxyTypes.cs b/src/AppConfiguration/generated/runtime/BuildTime/Models/PsProxyTypes.cs new file mode 100644 index 000000000000..ce79a53c7770 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/Models/PsProxyTypes.cs @@ -0,0 +1,499 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + internal class ProfileGroup + { + public string ProfileName { get; } + public Variant[] Variants { get; } + public string ProfileFolder { get; } + + public ProfileGroup(Variant[] variants, string profileName = NoProfiles) + { + ProfileName = profileName; + Variants = variants; + ProfileFolder = ProfileName != NoProfiles ? ProfileName : String.Empty; + } + } + + internal class VariantGroup + { + public string ModuleName { get; } + public string CmdletName { get; } + public string CmdletVerb { get; } + public string CmdletNoun { get; } + public string ProfileName { get; } + public Variant[] Variants { get; } + public ParameterGroup[] ParameterGroups { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + + public string[] Aliases { get; } + public PSTypeName[] OutputTypes { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + public string DefaultParameterSetName { get; } + public bool HasMultipleVariants { get; } + public PsHelpInfo HelpInfo { get; } + public bool IsGenerated { get; } + public bool IsInternal { get; } + + public string OutputFolder { get; } + public string FileName { get; } + public string FilePath { get; } + + public CommentInfo CommentInfo { get; } + + public VariantGroup(string moduleName, string cmdletName, Variant[] variants, string outputFolder, string profileName = NoProfiles, bool isTest = false, bool isInternal = false) + { + ModuleName = moduleName; + CmdletName = cmdletName; + var cmdletNameParts = CmdletName.Split('-'); + CmdletVerb = cmdletNameParts.First(); + CmdletNoun = cmdletNameParts.Last(); + ProfileName = profileName; + Variants = variants; + ParameterGroups = Variants.ToParameterGroups().OrderBy(pg => pg.OrderCategory).ThenByDescending(pg => pg.IsMandatory).ToArray(); + var aliasDuplicates = ParameterGroups.SelectMany(pg => pg.Aliases) + //https://stackoverflow.com/a/18547390/294804 + .GroupBy(a => a).Where(g => g.Count() > 1).Select(g => g.Key).ToArray(); + if (aliasDuplicates.Any()) + { + throw new ParsingMetadataException($"The alias(es) [{String.Join(", ", aliasDuplicates)}] are defined on multiple parameters for cmdlet '{CmdletName}', which is not supported."); + } + ComplexInterfaceInfos = ParameterGroups.Where(pg => !pg.DontShow && pg.IsComplexInterface).OrderBy(pg => pg.ParameterName).Select(pg => pg.ComplexInterfaceInfo).ToArray(); + + Aliases = Variants.SelectMany(v => v.Attributes).ToAliasNames().ToArray(); + OutputTypes = Variants.SelectMany(v => v.Info.OutputType).Where(ot => ot.Type != null).GroupBy(ot => ot.Type).Select(otg => otg.First()).ToArray(); + SupportsShouldProcess = Variants.Any(v => v.SupportsShouldProcess); + SupportsPaging = Variants.Any(v => v.SupportsPaging); + DefaultParameterSetName = DetermineDefaultParameterSetName(); + HasMultipleVariants = Variants.Length > 1; + HelpInfo = Variants.Select(v => v.HelpInfo).FirstOrDefault() ?? new PsHelpInfo(); + IsGenerated = Variants.All(v => v.Attributes.OfType().Any()); + IsInternal = isInternal; + + OutputFolder = outputFolder; + FileName = $"{CmdletName}{(isTest ? ".Tests" : String.Empty)}.ps1"; + FilePath = Path.Combine(OutputFolder, FileName); + + CommentInfo = new CommentInfo(this); + } + + private string DetermineDefaultParameterSetName() + { + var defaultParameterSet = Variants + .Select(v => v.Metadata.DefaultParameterSetName) + .LastOrDefault(dpsn => dpsn.IsValidDefaultParameterSetName()); + + if (String.IsNullOrEmpty(defaultParameterSet)) + { + var variantParamCountGroups = Variants + .Select(v => ( + variant: v.VariantName, + paramCount: v.CmdletOnlyParameters.Count(p => p.IsMandatory), + isSimple: v.CmdletOnlyParameters.Where(p => p.IsMandatory).All(p => p.ParameterType.IsPsSimple()))) + .GroupBy(vpc => vpc.isSimple) + .ToArray(); + var variantParameterCounts = (variantParamCountGroups.Any(g => g.Key) ? variantParamCountGroups.Where(g => g.Key) : variantParamCountGroups).SelectMany(g => g).ToArray(); + var smallestParameterCount = variantParameterCounts.Min(vpc => vpc.paramCount); + defaultParameterSet = variantParameterCounts.First(vpc => vpc.paramCount == smallestParameterCount).variant; + } + + return defaultParameterSet; + } + } + + internal class Variant + { + public string CmdletName { get; } + public string VariantName { get; } + public CommandInfo Info { get; } + public CommandMetadata Metadata { get; } + public PsHelpInfo HelpInfo { get; } + public bool HasParameterSets { get; } + public bool IsFunction { get; } + public string PrivateModuleName { get; } + public string PrivateCmdletName { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public Attribute[] Attributes { get; } + public Parameter[] Parameters { get; } + public Parameter[] CmdletOnlyParameters { get; } + public bool IsInternal { get; } + public bool IsDoNotExport { get; } + public string[] Profiles { get; } + + public Variant(string cmdletName, string variantName, CommandInfo info, CommandMetadata metadata, bool hasParameterSets = false, PsHelpInfo helpInfo = null) + { + CmdletName = cmdletName; + VariantName = variantName; + Info = info; + HelpInfo = helpInfo ?? new PsHelpInfo(); + Metadata = metadata; + HasParameterSets = hasParameterSets; + IsFunction = Info.CommandType == CommandTypes.Function; + PrivateModuleName = Info.Source; + PrivateCmdletName = Metadata.Name; + SupportsShouldProcess = Metadata.SupportsShouldProcess; + SupportsPaging = Metadata.SupportsPaging; + + Attributes = this.ToAttributes(); + Parameters = this.ToParameters().OrderBy(p => p.OrderCategory).ThenByDescending(p => p.IsMandatory).ToArray(); + IsInternal = Attributes.OfType().Any(); + IsDoNotExport = Attributes.OfType().Any(); + CmdletOnlyParameters = Parameters.Where(p => !p.Categories.Any(c => c == ParameterCategory.Azure || c == ParameterCategory.Runtime)).ToArray(); + Profiles = Attributes.OfType().SelectMany(pa => pa.Profiles).ToArray(); + } + } + + internal class ParameterGroup + { + public string ParameterName { get; } + public Parameter[] Parameters { get; } + + public string[] VariantNames { get; } + public string[] AllVariantNames { get; } + public bool HasAllVariants { get; } + public Type ParameterType { get; } + public string Description { get; } + + public string[] Aliases { get; } + public bool HasValidateNotNull { get; } + public CompleterInfo CompleterInfo { get; } + public DefaultInfo DefaultInfo { get; } + public bool HasDefaultInfo { get; } + public ParameterCategory OrderCategory { get; } + public bool DontShow { get; } + public bool IsMandatory { get; } + public bool SupportsWildcards { get; } + public bool IsComplexInterface { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public InfoAttribute InfoAttribute { get; } + + public int? FirstPosition { get; } + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public bool IsInputType { get; } + + public ParameterGroup(string parameterName, Parameter[] parameters, string[] allVariantNames) + { + ParameterName = parameterName; + Parameters = parameters; + + VariantNames = Parameters.Select(p => p.VariantName).ToArray(); + AllVariantNames = allVariantNames; + HasAllVariants = VariantNames.Any(vn => vn == AllParameterSets) || !AllVariantNames.Except(VariantNames).Any(); + var types = Parameters.Select(p => p.ParameterType).Distinct().ToArray(); + if (types.Length > 1) + { + throw new ParsingMetadataException($"The parameter '{ParameterName}' has multiple parameter types [{String.Join(", ", types.Select(t => t.Name))}] defined, which is not supported."); + } + ParameterType = types.First(); + Description = Parameters.Select(p => p.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + + Aliases = Parameters.SelectMany(p => p.Attributes).ToAliasNames().ToArray(); + HasValidateNotNull = Parameters.SelectMany(p => p.Attributes.OfType()).Any(); + CompleterInfo = Parameters.Select(p => p.CompleterInfoAttribute).FirstOrDefault()?.ToCompleterInfo() + ?? Parameters.Select(p => p.ArgumentCompleterAttribute).FirstOrDefault()?.ToCompleterInfo(); + DefaultInfo = Parameters.Select(p => p.DefaultInfoAttribute).FirstOrDefault()?.ToDefaultInfo(this) + ?? Parameters.Select(p => p.DefaultValueAttribute).FirstOrDefault(dv => dv != null)?.ToDefaultInfo(this); + HasDefaultInfo = DefaultInfo != null && !String.IsNullOrEmpty(DefaultInfo.Script); + // When DefaultInfo is present, force all parameters from this group to be optional. + if (HasDefaultInfo) + { + foreach (var parameter in Parameters) + { + parameter.IsMandatory = false; + } + } + OrderCategory = Parameters.Select(p => p.OrderCategory).Distinct().DefaultIfEmpty(ParameterCategory.Body).Min(); + DontShow = Parameters.All(p => p.DontShow); + IsMandatory = HasAllVariants && Parameters.Any(p => p.IsMandatory); + SupportsWildcards = Parameters.Any(p => p.SupportsWildcards); + IsComplexInterface = Parameters.Any(p => p.IsComplexInterface); + ComplexInterfaceInfo = Parameters.Where(p => p.IsComplexInterface).Select(p => p.ComplexInterfaceInfo).FirstOrDefault(); + InfoAttribute = Parameters.Select(p => p.InfoAttribute).First(); + + FirstPosition = Parameters.Select(p => p.Position).FirstOrDefault(p => p != null); + ValueFromPipeline = Parameters.Any(p => p.ValueFromPipeline); + ValueFromPipelineByPropertyName = Parameters.Any(p => p.ValueFromPipelineByPropertyName); + IsInputType = ValueFromPipeline || ValueFromPipelineByPropertyName; + } + } + + internal class Parameter + { + public string VariantName { get; } + public string ParameterName { get; } + public ParameterMetadata Metadata { get; } + public PsParameterHelpInfo HelpInfo { get; } + public Type ParameterType { get; } + + public Attribute[] Attributes { get; } + public ParameterCategory[] Categories { get; } + public ParameterCategory OrderCategory { get; } + public PSDefaultValueAttribute DefaultValueAttribute { get; } + public DefaultInfoAttribute DefaultInfoAttribute { get; } + public ParameterAttribute ParameterAttribute { get; } + public bool SupportsWildcards { get; } + public CompleterInfoAttribute CompleterInfoAttribute { get; } + public ArgumentCompleterAttribute ArgumentCompleterAttribute { get; } + + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public int? Position { get; } + public bool DontShow { get; } + public bool IsMandatory { get; set; } + + public InfoAttribute InfoAttribute { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public bool IsComplexInterface { get; } + public string Description { get; } + + public Parameter(string variantName, string parameterName, ParameterMetadata metadata, PsParameterHelpInfo helpInfo = null) + { + VariantName = variantName; + ParameterName = parameterName; + Metadata = metadata; + HelpInfo = helpInfo ?? new PsParameterHelpInfo(); + + Attributes = Metadata.Attributes.ToArray(); + ParameterType = Attributes.OfType().FirstOrDefault()?.Type ?? Metadata.ParameterType; + Categories = Attributes.OfType().SelectMany(ca => ca.Categories).Distinct().ToArray(); + OrderCategory = Categories.DefaultIfEmpty(ParameterCategory.Body).Min(); + DefaultValueAttribute = Attributes.OfType().FirstOrDefault(); + DefaultInfoAttribute = Attributes.OfType().FirstOrDefault(); + ParameterAttribute = Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == VariantName || pa.ParameterSetName == AllParameterSets); + if (ParameterAttribute == null) + { + throw new ParsingMetadataException($"The variant '{VariantName}' has multiple parameter sets defined, which is not supported."); + } + SupportsWildcards = Attributes.OfType().Any(); + CompleterInfoAttribute = Attributes.OfType().FirstOrDefault(); + ArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(); + + ValueFromPipeline = ParameterAttribute.ValueFromPipeline; + ValueFromPipelineByPropertyName = ParameterAttribute.ValueFromPipelineByPropertyName; + Position = ParameterAttribute.Position == Int32.MinValue ? (int?)null : ParameterAttribute.Position; + DontShow = ParameterAttribute.DontShow; + IsMandatory = ParameterAttribute.Mandatory; + + var complexParameterName = ParameterName.ToUpperInvariant(); + var complexMessage = $"{Environment.NewLine}To construct, see NOTES section for {complexParameterName} properties and create a hash table."; + var description = ParameterAttribute.HelpMessage.NullIfEmpty() ?? HelpInfo.Description.NullIfEmpty() ?? InfoAttribute?.Description.NullIfEmpty() ?? String.Empty; + // Remove the complex type message as it will be reinserted if this is a complex type + description = description.NormalizeNewLines().Replace(complexMessage, String.Empty).Replace(complexMessage.ToPsSingleLine(), String.Empty); + // Make an InfoAttribute for processing only if one isn't provided + InfoAttribute = Attributes.OfType().FirstOrDefault() ?? new InfoAttribute { PossibleTypes = new[] { ParameterType.Unwrap() }, Required = IsMandatory }; + // Set the description if the InfoAttribute does not have one since they are exported without a description + InfoAttribute.Description = String.IsNullOrEmpty(InfoAttribute.Description) ? description : InfoAttribute.Description; + ComplexInterfaceInfo = InfoAttribute.ToComplexInterfaceInfo(complexParameterName, ParameterType, true); + IsComplexInterface = ComplexInterfaceInfo.IsComplexInterface; + Description = $"{description}{(IsComplexInterface ? complexMessage : String.Empty)}"; + } + } + + internal class ComplexInterfaceInfo + { + public InfoAttribute InfoAttribute { get; } + + public string Name { get; } + public Type Type { get; } + public bool Required { get; } + public bool ReadOnly { get; } + public string Description { get; } + + public ComplexInterfaceInfo[] NestedInfos { get; } + public bool IsComplexInterface { get; } + + public ComplexInterfaceInfo(string name, Type type, InfoAttribute infoAttribute, bool? required, List seenTypes) + { + Name = name; + Type = type; + InfoAttribute = infoAttribute; + + Required = required ?? InfoAttribute.Required; + ReadOnly = InfoAttribute.ReadOnly; + Description = InfoAttribute.Description.ToPsSingleLine(); + + var unwrappedType = Type.Unwrap(); + var hasBeenSeen = seenTypes?.Contains(unwrappedType) ?? false; + (seenTypes ?? (seenTypes = new List())).Add(unwrappedType); + NestedInfos = hasBeenSeen ? new ComplexInterfaceInfo[]{} : + unwrappedType.GetInterfaces() + .Concat(InfoAttribute.PossibleTypes) + .SelectMany(pt => pt.GetProperties() + .SelectMany(pi => pi.GetCustomAttributes(true).OfType() + .Select(ia => ia.ToComplexInterfaceInfo(pi.Name, pi.PropertyType, seenTypes: seenTypes)))) + .Where(cii => !cii.ReadOnly).OrderByDescending(cii => cii.Required).ToArray(); + // https://stackoverflow.com/a/503359/294804 + var associativeArrayInnerType = Type.GetInterfaces() + .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>)) + ?.GetTypeInfo().GetGenericArguments().First(); + if (!hasBeenSeen && associativeArrayInnerType != null) + { + var anyInfo = new InfoAttribute { Description = "This indicates any property can be added to this object." }; + NestedInfos = NestedInfos.Prepend(anyInfo.ToComplexInterfaceInfo("(Any)", associativeArrayInnerType)).ToArray(); + } + IsComplexInterface = NestedInfos.Any(); + } + } + + internal class CommentInfo + { + public string Description { get; } + public string Synopsis { get; } + + public string[] Examples { get; } + public string[] Inputs { get; } + public string[] Outputs { get; } + + public string OnlineVersion { get; } + public string[] RelatedLinks { get; } + + private const string HelpLinkPrefix = @"https://docs.microsoft.com/en-us/powershell/module/"; + + public CommentInfo(VariantGroup variantGroup) + { + var helpInfo = variantGroup.HelpInfo; + Description = variantGroup.Variants.SelectMany(v => v.Attributes).OfType().FirstOrDefault()?.Description.NullIfEmpty() + ?? helpInfo.Description.EmptyIfNull(); + // If there is no Synopsis, PowerShell may put in the Syntax string as the Synopsis. This seems unintended, so we remove the Synopsis in this situation. + var synopsis = helpInfo.Synopsis.EmptyIfNull().Trim().StartsWith(variantGroup.CmdletName) ? String.Empty : helpInfo.Synopsis; + Synopsis = synopsis.NullIfEmpty() ?? Description; + + Examples = helpInfo.Examples.Select(rl => rl.Code).ToArray(); + + Inputs = (variantGroup.ParameterGroups.Where(pg => pg.IsInputType).Select(pg => pg.ParameterType.FullName).ToArray().NullIfEmpty() ?? + helpInfo.InputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(it => it.Name).ToArray()) + .Where(i => i != "None").Distinct().OrderBy(i => i).ToArray(); + Outputs = (variantGroup.OutputTypes.Select(ot => ot.Type.FullName).ToArray().NullIfEmpty() ?? + helpInfo.OutputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(ot => ot.Name).ToArray()) + .Where(o => o != "None").Distinct().OrderBy(o => o).ToArray(); + + OnlineVersion = helpInfo.OnlineVersion?.Uri.NullIfEmpty() ?? $@"{HelpLinkPrefix}{variantGroup.ModuleName.ToLowerInvariant()}/{variantGroup.CmdletName.ToLowerInvariant()}"; + RelatedLinks = helpInfo.RelatedLinks.Select(rl => rl.Text).ToArray(); + } + } + + internal class CompleterInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public Type Type { get; } + public bool IsTypeCompleter { get; } + + public CompleterInfo(CompleterInfoAttribute infoAttribute) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + } + + public CompleterInfo(ArgumentCompleterAttribute completerAttribute) + { + Script = completerAttribute.ScriptBlock?.ToString(); + if (completerAttribute.Type != null) + { + Type = completerAttribute.Type; + IsTypeCompleter = true; + } + } + } + + internal class DefaultInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public ParameterGroup ParameterGroup { get; } + + public DefaultInfo(DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + ParameterGroup = parameterGroup; + } + + public DefaultInfo(PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) + { + Description = defaultValueAttribute.Help; + ParameterGroup = parameterGroup; + if (defaultValueAttribute.Value != null) + { + Script = defaultValueAttribute.Value.ToString(); + } + } + } + + internal static class PsProxyTypeExtensions + { + public const string NoProfiles = "__NoProfiles"; + + public static bool IsValidDefaultParameterSetName(this string parameterSetName) => + !String.IsNullOrEmpty(parameterSetName) && parameterSetName != AllParameterSets; + + public static Variant[] ToVariants(this CommandInfo info, PsHelpInfo helpInfo) + { + var metadata = new CommandMetadata(info); + var privateCmdletName = metadata.Name.Split('!').First(); + var parts = privateCmdletName.Split('_'); + return parts.Length > 1 + ? new[] { new Variant(parts[0], parts[1], info, metadata, helpInfo: helpInfo) } + // Process multiple parameter sets, so we declare a variant per parameter set. + : info.ParameterSets.Select(ps => new Variant(privateCmdletName, ps.Name, info, metadata, true, helpInfo)).ToArray(); + } + + public static Variant[] ToVariants(this CmdletAndHelpInfo info) => info.CommandInfo.ToVariants(info.HelpInfo); + + public static Variant[] ToVariants(this CommandInfo info, PSObject helpInfo = null) => info.ToVariants(helpInfo?.ToPsHelpInfo()); + + public static Parameter[] ToParameters(this Variant variant) + { + var parameters = variant.Metadata.Parameters.AsEnumerable(); + var parameterHelp = variant.HelpInfo.Parameters.AsEnumerable(); + if (variant.HasParameterSets) + { + parameters = parameters.Where(p => p.Value.ParameterSets.Keys.Any(k => k == variant.VariantName || k == AllParameterSets)); + parameterHelp = parameterHelp.Where(ph => !ph.ParameterSetNames.Any() || ph.ParameterSetNames.Any(psn => psn == variant.VariantName || psn == AllParameterSets)); + } + return parameters.Select(p => new Parameter(variant.VariantName, p.Key, p.Value, parameterHelp.FirstOrDefault(ph => ph.Name == p.Key))).ToArray(); + } + + public static Attribute[] ToAttributes(this Variant variant) => variant.IsFunction + ? ((FunctionInfo)variant.Info).ScriptBlock.Attributes.ToArray() + : variant.Metadata.CommandType.GetCustomAttributes(false).Cast().ToArray(); + + public static IEnumerable ToParameterGroups(this Variant[] variants) + { + var allVariantNames = variants.Select(vg => vg.VariantName).ToArray(); + return variants + .SelectMany(v => v.Parameters) + .GroupBy(p => p.ParameterName, StringComparer.InvariantCultureIgnoreCase) + .Select(pg => new ParameterGroup(pg.Key, pg.Select(p => p).ToArray(), allVariantNames)); + } + + public static ComplexInterfaceInfo ToComplexInterfaceInfo(this InfoAttribute infoAttribute, string name, Type type, bool? required = null, List seenTypes = null) + => new ComplexInterfaceInfo(name, type, infoAttribute, required, seenTypes); + + public static CompleterInfo ToCompleterInfo(this CompleterInfoAttribute infoAttribute) => new CompleterInfo(infoAttribute); + public static CompleterInfo ToCompleterInfo(this ArgumentCompleterAttribute completerAttribute) => new CompleterInfo(completerAttribute); + + public static DefaultInfo ToDefaultInfo(this DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) => new DefaultInfo(infoAttribute, parameterGroup); + public static DefaultInfo ToDefaultInfo(this PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) => new DefaultInfo(defaultValueAttribute, parameterGroup); + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/PsAttributes.cs b/src/AppConfiguration/generated/runtime/BuildTime/PsAttributes.cs new file mode 100644 index 000000000000..aeef668f3c1d --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/PsAttributes.cs @@ -0,0 +1,114 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration +{ + [AttributeUsage(AttributeTargets.Class)] + public class DescriptionAttribute : Attribute + { + public string Description { get; } + + public DescriptionAttribute(string description) + { + Description = description; + } + } + + [AttributeUsage(AttributeTargets.Class)] + public class DoNotExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class InternalExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class GeneratedAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public class DoNotFormatAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class ProfileAttribute : Attribute + { + public string[] Profiles { get; } + + public ProfileAttribute(params string[] profiles) + { + Profiles = profiles; + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class CategoryAttribute : Attribute + { + public ParameterCategory[] Categories { get; } + + public CategoryAttribute(params ParameterCategory[] categories) + { + Categories = categories; + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class ExportAsAttribute : Attribute + { + public Type Type { get; set; } + + public ExportAsAttribute(Type type) + { + Type = type; + } + } + + public enum ParameterCategory + { + // Note: Order is significant + Uri = 0, + Path, + Query, + Header, + Cookie, + Body, + Azure, + Runtime + } + + [AttributeUsage(AttributeTargets.Property)] + public class OriginAttribute : Attribute + { + public PropertyOrigin Origin { get; } + + public OriginAttribute(PropertyOrigin origin) + { + Origin = origin; + } + } + + public enum PropertyOrigin + { + // Note: Order is significant + Inherited = 0, + Owned, + Inlined + } + + [AttributeUsage(AttributeTargets.Property)] + public class FormatTableAttribute : Attribute + { + public int Index { get; set; } = -1; + public bool HasIndex => Index != -1; + public string Label { get; set; } + public int Width { get; set; } = -1; + public bool HasWidth => Width != -1; + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/PsExtensions.cs b/src/AppConfiguration/generated/runtime/BuildTime/PsExtensions.cs new file mode 100644 index 000000000000..7293613b99c5 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/PsExtensions.cs @@ -0,0 +1,160 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + internal static class PsExtensions + { + // https://stackoverflow.com/a/863944/294804 + // https://stackoverflow.com/a/4452598/294804 + // https://stackoverflow.com/a/28701974/294804 + // Note: This will unwrap nested collections, but we don't generate nested collections. + public static Type Unwrap(this Type type) + { + if (type.IsArray) + { + return type.GetElementType().Unwrap(); + } + + var typeInfo = type.GetTypeInfo(); + if (typeInfo.IsGenericType + && (typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>) || typeof(IEnumerable<>).IsAssignableFrom(type))) + { + return typeInfo.GetGenericArguments().First().Unwrap(); + } + + return type; + } + + // https://stackoverflow.com/a/863944/294804 + private static bool IsSimple(this Type type) + { + var typeInfo = type.GetTypeInfo(); + return typeInfo.IsPrimitive + || typeInfo.IsEnum + || type == typeof(string) + || type == typeof(decimal); + } + + // https://stackoverflow.com/a/32025393/294804 + private static bool HasImplicitConversion(this Type baseType, Type targetType) => + baseType.GetMethods(BindingFlags.Public | BindingFlags.Static) + .Where(mi => mi.Name == "op_Implicit" && mi.ReturnType == targetType) + .Any(mi => mi.GetParameters().FirstOrDefault()?.ParameterType == baseType); + + public static bool IsPsSimple(this Type type) + { + var unwrappedType = type.Unwrap(); + return unwrappedType.IsSimple() + || unwrappedType == typeof(SwitchParameter) + || unwrappedType == typeof(Hashtable) + || unwrappedType == typeof(PSCredential) + || unwrappedType == typeof(ScriptBlock) + || unwrappedType == typeof(DateTime) + || unwrappedType == typeof(Uri) + || unwrappedType.HasImplicitConversion(typeof(string)); + } + + public static string ToPsList(this IEnumerable items) => String.Join(", ", items.Select(i => $"'{i}'")); + + public static IEnumerable ToAliasNames(this IEnumerable attributes) => attributes.OfType().SelectMany(aa => aa.AliasNames).Distinct(); + + public static bool IsArrayAndElementTypeIsT(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return itemType.IsArray && !tType.IsArray && tType.IsAssignableFrom(itemType.GetElementType()); + } + + public static bool IsTArrayAndElementTypeIsItem(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return !itemType.IsArray && tType.IsArray && (tType.GetElementType()?.IsAssignableFrom(itemType) ?? false); + } + + public static bool IsTypeOrArrayOfType(this object item) => item is T || item.IsArrayAndElementTypeIsT() || item.IsTArrayAndElementTypeIsItem(); + + public static T NormalizeArrayType(this object item) + { + if (item is T result) + { + return result; + } + + if (item.IsArrayAndElementTypeIsT()) + { + var array = (T[])Convert.ChangeType(item, typeof(T[])); + return array.FirstOrDefault(); + } + + if (item.IsTArrayAndElementTypeIsItem()) + { + var tType = typeof(T); + var array = Array.CreateInstance(tType.GetElementType(), 1); + array.SetValue(item, 0); + return (T)Convert.ChangeType(array, tType); + } + + return default(T); + } + + public static T GetNestedProperty(this PSObject psObject, params string[] names) => psObject.Properties.GetNestedProperty(names); + + public static T GetNestedProperty(this PSMemberInfoCollection properties, params string[] names) + { + var lastName = names.Last(); + var nestedProperties = names.Take(names.Length - 1).Aggregate(properties, (p, n) => p?.GetProperty(n)?.Properties); + return nestedProperties != null ? nestedProperties.GetProperty(lastName) : default(T); + } + + public static T GetProperty(this PSObject psObject, string name) => psObject.Properties.GetProperty(name); + + public static T GetProperty(this PSMemberInfoCollection properties, string name) + { + switch (properties[name]?.Value) + { + case PSObject psObject when psObject.BaseObject is PSCustomObject && psObject.ImmediateBaseObject.IsTypeOrArrayOfType(): + return psObject.ImmediateBaseObject.NormalizeArrayType(); + case PSObject psObject when psObject.BaseObject.IsTypeOrArrayOfType(): + return psObject.BaseObject.NormalizeArrayType(); + case object value when value.IsTypeOrArrayOfType(): + return value.NormalizeArrayType(); + default: + return default(T); + } + } + + public static IEnumerable RunScript(this PSCmdlet cmdlet, string script) + => PsHelpers.RunScript(cmdlet.InvokeCommand, script); + + public static void RunScript(this PSCmdlet cmdlet, string script) + => cmdlet.RunScript(script); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, string script) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, script); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, string script) + => engineIntrinsics.RunScript(script); + + public static IEnumerable RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => PsHelpers.RunScript(cmdlet.InvokeCommand, block.ToString()); + + public static void RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => cmdlet.RunScript(block.ToString()); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, block.ToString()); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => engineIntrinsics.RunScript(block.ToString()); + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/PsHelpers.cs b/src/AppConfiguration/generated/runtime/BuildTime/PsHelpers.cs new file mode 100644 index 000000000000..ac381a5e4448 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/PsHelpers.cs @@ -0,0 +1,104 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using Pwsh = System.Management.Automation.PowerShell; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + internal static class PsHelpers + { + public static IEnumerable RunScript(string script) + => Pwsh.Create().AddScript(script).Invoke(); + + public static void RunScript(string script) + => RunScript(script); + + public static IEnumerable RunScript(CommandInvocationIntrinsics cii, string script) + => cii.InvokeScript(script).Select(o => o?.BaseObject).Where(o => o != null).OfType(); + + public static void RunScript(CommandInvocationIntrinsics cii, string script) + => RunScript(cii, script); + + public static IEnumerable GetModuleCmdlets(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletsCommand = String.Join(" + ", modulePaths.Select(mp => $"(Get-Command -Module (Import-Module '{mp}' -PassThru))")); + return (cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand)) + .Where(ci => ci.CommandType != CommandTypes.Alias); + } + + public static IEnumerable GetModuleCmdlets(params string[] modulePaths) + => GetModuleCmdlets(null, modulePaths); + + public static IEnumerable GetScriptCmdlets(PSCmdlet cmdlet, string scriptFolder) + { + // https://stackoverflow.com/a/40969712/294804 + var getCmdletsCommand = $@" +$currentFunctions = Get-ChildItem function: +Get-ChildItem -Path '{scriptFolder}' -Recurse -Include '*.ps1' -File | ForEach-Object {{ . $_.FullName }} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} +"; + return cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand); + } + + public static IEnumerable GetScriptCmdlets(string scriptFolder) + => GetScriptCmdlets(null, scriptFolder); + + public static IEnumerable GetScriptHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var importModules = String.Join(Environment.NewLine, modulePaths.Select(mp => $"Import-Module '{mp}'")); + var getHelpCommand = $@" +$currentFunctions = Get-ChildItem function: +{importModules} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} | ForEach-Object {{ Get-Help -Name $_.Name -Full }} +"; + return cmdlet?.RunScript(getHelpCommand) ?? RunScript(getHelpCommand); + } + + public static IEnumerable GetScriptHelpInfo(params string[] modulePaths) + => GetScriptHelpInfo(null, modulePaths); + + public static IEnumerable GetModuleCmdletsAndHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletAndHelp = String.Join(" + ", modulePaths.Select(mp => + $@"(Get-Command -Module (Import-Module '{mp}' -PassThru) | Where-Object {{ $_.CommandType -ne 'Alias' }} | ForEach-Object {{ @{{ CommandInfo = $_; HelpInfo = ( invoke-command {{ try {{ Get-Help -Name $_.Name -Full }} catch{{ '' }} }} ) }} }})" + )); + return (cmdlet?.RunScript(getCmdletAndHelp) ?? RunScript(getCmdletAndHelp)) + .Select(h => new CmdletAndHelpInfo { CommandInfo = (h["CommandInfo"] as PSObject)?.BaseObject as CommandInfo, HelpInfo = h["HelpInfo"] as PSObject }); + } + + public static IEnumerable GetModuleCmdletsAndHelpInfo(params string[] modulePaths) + => GetModuleCmdletsAndHelpInfo(null, modulePaths); + + public static CmdletAndHelpInfo ToCmdletAndHelpInfo(this CommandInfo commandInfo, PSObject helpInfo) => new CmdletAndHelpInfo { CommandInfo = commandInfo, HelpInfo = helpInfo }; + + public const string Psd1Indent = " "; + public const string GuidStart = Psd1Indent + "GUID"; + + public static Guid ReadGuidFromPsd1(string psd1Path) + { + var guid = Guid.NewGuid(); + if (File.Exists(psd1Path)) + { + var currentGuid = File.ReadAllLines(psd1Path) + .FirstOrDefault(l => l.StartsWith(GuidStart))?.Split(new[] { " = " }, StringSplitOptions.RemoveEmptyEntries) + .LastOrDefault()?.Replace("'", String.Empty); + guid = currentGuid != null ? Guid.Parse(currentGuid) : guid; + } + + return guid; + } + } + + internal class CmdletAndHelpInfo + { + public CommandInfo CommandInfo { get; set; } + public PSObject HelpInfo { get; set; } + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/StringExtensions.cs b/src/AppConfiguration/generated/runtime/BuildTime/StringExtensions.cs new file mode 100644 index 000000000000..8e7e631fa1da --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/StringExtensions.cs @@ -0,0 +1,24 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + internal static class StringExtensions + { + public static string NullIfEmpty(this string text) => String.IsNullOrEmpty(text) ? null : text; + public static string NullIfWhiteSpace(this string text) => String.IsNullOrWhiteSpace(text) ? null : text; + public static string EmptyIfNull(this string text) => text ?? String.Empty; + + public static bool? ToNullableBool(this string text) => String.IsNullOrEmpty(text) ? (bool?)null : Convert.ToBoolean(text.ToLowerInvariant()); + + public static string ToUpperFirstCharacter(this string text) => String.IsNullOrEmpty(text) ? text : $"{text[0].ToString().ToUpperInvariant()}{text.Remove(0, 1)}"; + + public static string ReplaceNewLines(this string value, string replacer = " ", string[] newLineSymbols = null) + => (newLineSymbols ?? new []{ "\r\n", "\n" }).Aggregate(value.EmptyIfNull(), (current, symbol) => current.Replace(symbol, replacer)); + public static string NormalizeNewLines(this string value) => value.ReplaceNewLines("\u00A0").Replace("\u00A0", Environment.NewLine); + } +} diff --git a/src/AppConfiguration/generated/runtime/BuildTime/XmlExtensions.cs b/src/AppConfiguration/generated/runtime/BuildTime/XmlExtensions.cs new file mode 100644 index 000000000000..b6b888f15232 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/BuildTime/XmlExtensions.cs @@ -0,0 +1,28 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.IO; +using System.Xml; +using System.Xml.Serialization; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + internal static class XmlExtensions + { + public static string ToXmlString(this T inputObject, bool excludeDeclaration = false) + { + var serializer = new XmlSerializer(typeof(T)); + //https://stackoverflow.com/a/760290/294804 + //https://stackoverflow.com/a/3732234/294804 + var namespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }); + var xmlSettings = new XmlWriterSettings { OmitXmlDeclaration = excludeDeclaration, Indent = true }; + using (var stringWriter = new StringWriter()) + using (var xmlWriter = XmlWriter.Create(stringWriter, xmlSettings)) + { + serializer.Serialize(xmlWriter, inputObject, namespaces); + return stringWriter.ToString(); + } + } + } +} diff --git a/src/AppConfiguration/generated/runtime/CmdInfoHandler.cs b/src/AppConfiguration/generated/runtime/CmdInfoHandler.cs new file mode 100644 index 000000000000..30d6133e56bc --- /dev/null +++ b/src/AppConfiguration/generated/runtime/CmdInfoHandler.cs @@ -0,0 +1,40 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Management.Automation; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + using NextDelegate = Func, Task>, Task>; + using SignalDelegate = Func, Task>; + + public class CmdInfoHandler + { + private readonly string processRecordId; + private readonly string parameterSetName; + private readonly InvocationInfo invocationInfo; + + public CmdInfoHandler(string processRecordId, InvocationInfo invocationInfo, string parameterSetName) + { + this.processRecordId = processRecordId; + this.parameterSetName = parameterSetName; + this.invocationInfo = invocationInfo; + } + + public Task SendAsync(HttpRequestMessage request, CancellationToken token, Action cancel, SignalDelegate signal, NextDelegate next) + { + request.Headers.Add("x-ms-client-request-id", processRecordId); + request.Headers.Add("CommandName", invocationInfo?.InvocationName); + request.Headers.Add("FullCommandName", invocationInfo?.MyCommand?.Name); + request.Headers.Add("ParameterSetName", parameterSetName); + + // continue with pipeline. + return next(request, token, cancel, signal); + } + } +} diff --git a/src/AppConfiguration/generated/runtime/Conversions/ConversionException.cs b/src/AppConfiguration/generated/runtime/Conversions/ConversionException.cs new file mode 100644 index 000000000000..4c3be7975d1f --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/ConversionException.cs @@ -0,0 +1,17 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal class ConversionException : Exception + { + internal ConversionException(string message) + : base(message) { } + + internal ConversionException(JsonNode node, Type targetType) + : base($"Cannot convert '{node.Type}' to a {targetType.Name}") { } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/IJsonConverter.cs b/src/AppConfiguration/generated/runtime/Conversions/IJsonConverter.cs new file mode 100644 index 000000000000..476253843f34 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/IJsonConverter.cs @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal interface IJsonConverter + { + JsonNode ToJson(object value); + + object FromJson(JsonNode node); + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/BinaryConverter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/BinaryConverter.cs new file mode 100644 index 000000000000..2ddeddc70778 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/BinaryConverter.cs @@ -0,0 +1,24 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class BinaryConverter : JsonConverter + { + internal override JsonNode ToJson(byte[] value) => new XBinary(value); + + internal override byte[] FromJson(JsonNode node) + { + switch (node.Type) + { + case JsonType.String : return Convert.FromBase64String(node.ToString()); // Base64 Encoded + case JsonType.Binary : return ((XBinary)node).Value; + } + + throw new ConversionException(node, typeof(byte[])); + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/BooleanConverter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/BooleanConverter.cs new file mode 100644 index 000000000000..44671d2ff579 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/BooleanConverter.cs @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class BooleanConverter : JsonConverter + { + internal override JsonNode ToJson(bool value) => new JsonBoolean(value); + + internal override bool FromJson(JsonNode node) => (bool)node; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/DateTimeConverter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/DateTimeConverter.cs new file mode 100644 index 000000000000..2b0f156c4d3c --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/DateTimeConverter.cs @@ -0,0 +1,18 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class DateTimeConverter : JsonConverter + { + internal override JsonNode ToJson(DateTime value) + { + return new JsonDate(value); + } + + internal override DateTime FromJson(JsonNode node) => (DateTime)node; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs new file mode 100644 index 000000000000..c6967e1f30ba --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs @@ -0,0 +1,15 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class DateTimeOffsetConverter : JsonConverter + { + internal override JsonNode ToJson(DateTimeOffset value) => new JsonDate(value); + + internal override DateTimeOffset FromJson(JsonNode node) => (DateTimeOffset)node; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/DecimalConverter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/DecimalConverter.cs new file mode 100644 index 000000000000..a08a1c2a762a --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/DecimalConverter.cs @@ -0,0 +1,16 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class DecimalConverter : JsonConverter + { + internal override JsonNode ToJson(decimal value) => new JsonNumber(value.ToString()); + + internal override decimal FromJson(JsonNode node) + { + return (decimal)node; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/DoubleConverter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/DoubleConverter.cs new file mode 100644 index 000000000000..4fe35cc8cf0f --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/DoubleConverter.cs @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class DoubleConverter : JsonConverter + { + internal override JsonNode ToJson(double value) => new JsonNumber(value); + + internal override double FromJson(JsonNode node) => (double)node; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/EnumConverter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/EnumConverter.cs new file mode 100644 index 000000000000..8b50a6af1f27 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/EnumConverter.cs @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class EnumConverter : IJsonConverter + { + private readonly Type type; + + internal EnumConverter(Type type) + { + this.type = type ?? throw new ArgumentNullException(nameof(type)); + } + + public JsonNode ToJson(object value) => new JsonString(value.ToString()); + + public object FromJson(JsonNode node) + { + if (node.Type == JsonType.Number) + { + return Enum.ToObject(type, (int)node); + } + + return Enum.Parse(type, node.ToString(), ignoreCase: true); + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/GuidConverter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/GuidConverter.cs new file mode 100644 index 000000000000..a9fe3ed9ccaa --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/GuidConverter.cs @@ -0,0 +1,15 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class GuidConverter : JsonConverter + { + internal override JsonNode ToJson(Guid value) => new JsonString(value.ToString()); + + internal override Guid FromJson(JsonNode node) => (Guid)node; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/HashSet'1Converter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/HashSet'1Converter.cs new file mode 100644 index 000000000000..c0b640bc4c7e --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/HashSet'1Converter.cs @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Collections.Generic; +using System.Linq; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class HashSetConverter : JsonConverter> + { + internal override JsonNode ToJson(HashSet value) + { + return new XSet(value); + } + + internal override HashSet FromJson(JsonNode node) + { + var collection = node as ICollection; + + if (collection.Count == 0) return null; + + // TODO: Remove Linq depedency + return new HashSet(collection.Cast()); + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/Int16Converter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/Int16Converter.cs new file mode 100644 index 000000000000..8329654e3794 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/Int16Converter.cs @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class Int16Converter : JsonConverter + { + internal override JsonNode ToJson(short value) => new JsonNumber(value); + + internal override short FromJson(JsonNode node) => (short)node; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/Int32Converter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/Int32Converter.cs new file mode 100644 index 000000000000..f397dbaae80c --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/Int32Converter.cs @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class Int32Converter : JsonConverter + { + internal override JsonNode ToJson(int value) => new JsonNumber(value); + + internal override int FromJson(JsonNode node) => (int)node; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/Int64Converter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/Int64Converter.cs new file mode 100644 index 000000000000..67121e8b95f5 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/Int64Converter.cs @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class Int64Converter : JsonConverter + { + internal override JsonNode ToJson(long value) => new JsonNumber(value); + + internal override long FromJson(JsonNode node) => (long)node; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/JsonArrayConverter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/JsonArrayConverter.cs new file mode 100644 index 000000000000..784ae58dc9d5 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/JsonArrayConverter.cs @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class JsonArrayConverter : JsonConverter + { + internal override JsonNode ToJson(JsonArray value) => value; + + internal override JsonArray FromJson(JsonNode node) => (JsonArray)node; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/JsonObjectConverter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/JsonObjectConverter.cs new file mode 100644 index 000000000000..8cec341e0b15 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/JsonObjectConverter.cs @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class JsonObjectConverter : JsonConverter + { + internal override JsonNode ToJson(JsonObject value) => value; + + internal override JsonObject FromJson(JsonNode node) => (JsonObject)node; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/SingleConverter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/SingleConverter.cs new file mode 100644 index 000000000000..168a47215ecc --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/SingleConverter.cs @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class SingleConverter : JsonConverter + { + internal override JsonNode ToJson(float value) => new JsonNumber(value.ToString()); + + internal override float FromJson(JsonNode node) => (float)node; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/StringConverter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/StringConverter.cs new file mode 100644 index 000000000000..f3498674aa12 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/StringConverter.cs @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class StringConverter : JsonConverter + { + internal override JsonNode ToJson(string value) => new JsonString(value); + + internal override string FromJson(JsonNode node) => node.ToString(); + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/TimeSpanConverter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/TimeSpanConverter.cs new file mode 100644 index 000000000000..149928286335 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/TimeSpanConverter.cs @@ -0,0 +1,15 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class TimeSpanConverter : JsonConverter + { + internal override JsonNode ToJson(TimeSpan value) => new JsonString(value.ToString()); + + internal override TimeSpan FromJson(JsonNode node) => (TimeSpan)node; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/UInt16Converter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/UInt16Converter.cs new file mode 100644 index 000000000000..66b9167d8ecc --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/UInt16Converter.cs @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class UInt16Converter : JsonConverter + { + internal override JsonNode ToJson(ushort value) => new JsonNumber(value); + + internal override ushort FromJson(JsonNode node) => (ushort)node; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/UInt32Converter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/UInt32Converter.cs new file mode 100644 index 000000000000..dc260647981d --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/UInt32Converter.cs @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class UInt32Converter : JsonConverter + { + internal override JsonNode ToJson(uint value) => new JsonNumber(value); + + internal override uint FromJson(JsonNode node) => (uint)node; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/UInt64Converter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/UInt64Converter.cs new file mode 100644 index 000000000000..24a5c10ea33c --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/UInt64Converter.cs @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class UInt64Converter : JsonConverter + { + internal override JsonNode ToJson(ulong value) => new JsonNumber(value.ToString()); + + internal override ulong FromJson(JsonNode node) => (ulong)node; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/Instances/UriConverter.cs b/src/AppConfiguration/generated/runtime/Conversions/Instances/UriConverter.cs new file mode 100644 index 000000000000..5bcc6a945a5a --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/Instances/UriConverter.cs @@ -0,0 +1,15 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class UriConverter : JsonConverter + { + internal override JsonNode ToJson(Uri value) => new JsonString(value.AbsoluteUri); + + internal override Uri FromJson(JsonNode node) => (Uri)node; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/JsonConverter.cs b/src/AppConfiguration/generated/runtime/Conversions/JsonConverter.cs new file mode 100644 index 000000000000..5669c07296aa --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/JsonConverter.cs @@ -0,0 +1,21 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public abstract class JsonConverter : IJsonConverter + { + internal abstract T FromJson(JsonNode node); + + internal abstract JsonNode ToJson(T value); + + #region IConverter + + object IJsonConverter.FromJson(JsonNode node) => FromJson(node); + + JsonNode IJsonConverter.ToJson(object value) => ToJson((T)value); + + #endregion + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/JsonConverterAttribute.cs b/src/AppConfiguration/generated/runtime/Conversions/JsonConverterAttribute.cs new file mode 100644 index 000000000000..61ce892e26ef --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/JsonConverterAttribute.cs @@ -0,0 +1,18 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class JsonConverterAttribute : Attribute + { + internal JsonConverterAttribute(Type type) + { + Converter = (IJsonConverter)Activator.CreateInstance(type); + } + + internal IJsonConverter Converter { get; } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/JsonConverterFactory.cs b/src/AppConfiguration/generated/runtime/Conversions/JsonConverterFactory.cs new file mode 100644 index 000000000000..a224514883bc --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/JsonConverterFactory.cs @@ -0,0 +1,91 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class JsonConverterFactory + { + private static readonly Dictionary converters = new Dictionary(); + + static JsonConverterFactory() + { + AddInternal(new BooleanConverter()); + AddInternal(new DateTimeConverter()); + AddInternal(new DateTimeOffsetConverter()); + AddInternal(new BinaryConverter()); + AddInternal(new DecimalConverter()); + AddInternal(new DoubleConverter()); + AddInternal(new GuidConverter()); + AddInternal(new Int16Converter()); + AddInternal(new Int32Converter()); + AddInternal(new Int64Converter()); + AddInternal(new SingleConverter()); + AddInternal(new StringConverter()); + AddInternal(new TimeSpanConverter()); + AddInternal(new UInt16Converter()); + AddInternal(new UInt32Converter()); + AddInternal(new UInt64Converter()); + AddInternal(new UriConverter()); + + // Hash sets + AddInternal(new HashSetConverter()); + AddInternal(new HashSetConverter()); + AddInternal(new HashSetConverter()); + AddInternal(new HashSetConverter()); + AddInternal(new HashSetConverter()); + AddInternal(new HashSetConverter()); + + // JSON + + AddInternal(new JsonObjectConverter()); + AddInternal(new JsonArrayConverter()); + } + + internal static Dictionary Instances => converters; + + internal static IJsonConverter Get(Type type) + { + var details = TypeDetails.Get(type); + + if (details.JsonConverter == null) + { + throw new ConversionException($"No converter found for '{type.Name}'."); + } + + return details.JsonConverter; + } + + internal static bool TryGet(Type type, out IJsonConverter converter) + { + var typeDetails = TypeDetails.Get(type); + + converter = typeDetails.JsonConverter; + + return converter != null; + } + + private static void AddInternal(JsonConverter converter) + => converters.Add(typeof(T), converter); + + private static void AddInternal(IJsonConverter converter) + => converters.Add(typeof(T), converter); + + internal static void Add(JsonConverter converter) + { + if (converter == null) + { + throw new ArgumentNullException(nameof(converter)); + } + + AddInternal(converter); + + var type = TypeDetails.Get(); + + type.JsonConverter = converter; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Conversions/StringLikeConverter.cs b/src/AppConfiguration/generated/runtime/Conversions/StringLikeConverter.cs new file mode 100644 index 000000000000..fb625fb32e24 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Conversions/StringLikeConverter.cs @@ -0,0 +1,45 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class StringLikeConverter : IJsonConverter + { + private readonly Type type; + private readonly MethodInfo parseMethod; + + internal StringLikeConverter(Type type) + { + this.type = type ?? throw new ArgumentNullException(nameof(type)); + this.parseMethod = StringLikeHelper.GetParseMethod(type); + } + + public object FromJson(JsonNode node) => + parseMethod.Invoke(null, new[] { node.ToString() }); + + public JsonNode ToJson(object value) => new JsonString(value.ToString()); + } + + internal static class StringLikeHelper + { + private static readonly Type[] parseMethodParamaterTypes = new[] { typeof(string) }; + + internal static bool IsStringLike(Type type) + { + return GetParseMethod(type) != null; + } + + internal static MethodInfo GetParseMethod(Type type) + { + MethodInfo method = type.GetMethod("Parse", parseMethodParamaterTypes); + + if (method?.IsPublic != true) return null; + + return method; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Customizations/IJsonSerializable.cs b/src/AppConfiguration/generated/runtime/Customizations/IJsonSerializable.cs new file mode 100644 index 000000000000..7b873fe4f6b4 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Customizations/IJsonSerializable.cs @@ -0,0 +1,249 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json; +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + public interface IJsonSerializable + { + JsonNode ToJson(JsonObject container = null, SerializationMode serializationMode = SerializationMode.None); + } + internal static class JsonSerializable + { + /// + /// Serializes an enumerable and returns a JsonNode. + /// + /// an IEnumerable collection of items + /// A JsonNode that contains the collection of items serialized. + private static JsonNode ToJsonValue(System.Collections.IEnumerable enumerable) + { + if (enumerable != null) + { + // is it a byte array of some kind? + if (enumerable is System.Collections.Generic.IEnumerable byteEnumerable) + { + return new XBinary(System.Linq.Enumerable.ToArray(byteEnumerable)); + } + + var hasValues = false; + // just create an array of value nodes. + var result = new XNodeArray(); + foreach (var each in enumerable) + { + // we had at least one value. + hasValues = true; + + // try to serialize it. + var node = ToJsonValue(each); + if (null != node) + { + result.Add(node); + } + } + + // if we were able to add values, (or it was just empty), return it. + if (result.Count > 0 || !hasValues) + { + return result; + } + } + + // we couldn't serialize the values. Sorry. + return null; + } + + /// + /// Serializes a valuetype to a JsonNode. + /// + /// a ValueType (ie, a primitive, enum or struct) to be serialized + /// a JsonNode with the serialized value + private static JsonNode ToJsonValue(ValueType vValue) + { + // numeric type + if (vValue is SByte || vValue is Int16 || vValue is Int32 || vValue is Int64 || vValue is Byte || vValue is UInt16 || vValue is UInt32 || vValue is UInt64 || vValue is decimal || vValue is float || vValue is double) + { + return new JsonNumber(vValue.ToString()); + } + + // boolean type + if (vValue is bool bValue) + { + return new JsonBoolean(bValue); + } + + // dates + if (vValue is DateTime dtValue) + { + return new JsonDate(dtValue); + } + + // sorry, no idea. + return null; + } + /// + /// Attempts to serialize an object by using ToJson() or ToJsonString() if they exist. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + private static JsonNode TryToJsonValue(dynamic oValue) + { + object jsonValue = null; + dynamic v = oValue; + try + { + jsonValue = v.ToJson().ToString(); + } + catch + { + // no harm... + try + { + jsonValue = v.ToJsonString().ToString(); + } + catch + { + // no worries here either. + } + } + + // if we got something out, let's use it. + if (null != jsonValue) + { + // JsonNumber is really a literal json value. Just don't try to cast that back to an actual number, ok? + return new JsonNumber(jsonValue.ToString()); + } + + return null; + } + + /// + /// Serialize an object by using a variety of methods. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + internal static JsonNode ToJsonValue(object value) + { + // things that implement our interface are preferred. + if (value is Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IJsonSerializable jsonSerializable) + { + return jsonSerializable.ToJson(); + } + + // strings are easy. + if (value is string || value is char) + { + return new JsonString(value.ToString()); + } + + // value types are fairly straightforward (fallback to ToJson()/ToJsonString() or literal JsonString ) + if (value is System.ValueType vValue) + { + return ToJsonValue(vValue) ?? TryToJsonValue(vValue) ?? new JsonString(vValue.ToString()); + } + + // dictionaries are objects that should be able to serialize + if (value is System.Collections.Generic.IDictionary dictionary) + { + return Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.JsonSerializable.ToJson(dictionary, null); + } + + // enumerable collections are handled like arrays (again, fallback to ToJson()/ToJsonString() or literal JsonString) + if (value is System.Collections.IEnumerable enumerableValue) + { + // some kind of enumerable value + return ToJsonValue(enumerableValue) ?? TryToJsonValue(value) ?? new JsonString(value.ToString()); + } + + // at this point, we're going to fallback to a string literal here, since we really have no idea what it is. + return new JsonString(value.ToString()); + } + + internal static JsonObject ToJson(System.Collections.Generic.Dictionary dictionary, JsonObject container) => ToJson((System.Collections.Generic.IDictionary)dictionary, container); + + /// + /// Serializes a dictionary into a JsonObject container. + /// + /// The dictionary to serailize + /// the container to serialize the dictionary into + /// the container + internal static JsonObject ToJson(System.Collections.Generic.IDictionary dictionary, JsonObject container) + { + container = container ?? new JsonObject(); + if (dictionary != null && dictionary.Count > 0) + { + foreach (var key in dictionary) + { + // currently, we don't serialize null values. + if (null != key.Value) + { + container.Add(key.Key, ToJsonValue(key.Value)); + continue; + } + } + } + return container; + } + + internal static Func> DeserializeDictionary(Func> dictionaryFactory) + { + return (node) => FromJson(node, dictionaryFactory(), (object)(DeserializeDictionary(dictionaryFactory)) as Func); + } + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.Dictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) => FromJson(json, (System.Collections.Generic.IDictionary)container, objectFactory, excludes); + + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.IDictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) + { + if (null == json) + { + return container; + } + + foreach (var key in json.Keys) + { + if (true == excludes?.Contains(key)) + { + continue; + } + + var value = json[key]; + try + { + switch (value.Type) + { + case JsonType.Null: + // skip null values. + continue; + + case JsonType.Array: + case JsonType.Boolean: + case JsonType.Date: + case JsonType.Binary: + case JsonType.Number: + case JsonType.String: + container.Add(key, (V)value.ToValue()); + break; + case JsonType.Object: + if (objectFactory != null) + { + var v = objectFactory(value as JsonObject); + if (null != v) + { + container.Add(key, v); + } + } + break; + } + } + catch + { + } + } + return container; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Customizations/JsonArray.cs b/src/AppConfiguration/generated/runtime/Customizations/JsonArray.cs new file mode 100644 index 000000000000..134a568abc6f --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Customizations/JsonArray.cs @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public partial class JsonArray + { + internal override object ToValue() => Count == 0 ? new object[0] : System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Select(this, each => each.ToValue())); + } + + +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Customizations/JsonBoolean.cs b/src/AppConfiguration/generated/runtime/Customizations/JsonBoolean.cs new file mode 100644 index 000000000000..e97749019908 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Customizations/JsonBoolean.cs @@ -0,0 +1,16 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal partial class JsonBoolean + { + internal static JsonBoolean Create(bool? value) => value is bool b ? new JsonBoolean(b) : null; + internal bool ToBoolean() => Value; + + internal override object ToValue() => Value; + } + + +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Customizations/JsonNode.cs b/src/AppConfiguration/generated/runtime/Customizations/JsonNode.cs new file mode 100644 index 000000000000..7301ff2e873f --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Customizations/JsonNode.cs @@ -0,0 +1,21 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + using System; + using System.Collections.Generic; + + public partial class JsonNode + { + /// + /// Returns the content of this node as the underlying value. + /// Will default to the string representation if not overridden in child classes. + /// + /// an object with the underlying value of the node. + internal virtual object ToValue() { + return this.ToString(); + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Customizations/JsonNumber.cs b/src/AppConfiguration/generated/runtime/Customizations/JsonNumber.cs new file mode 100644 index 000000000000..38f17b924af2 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Customizations/JsonNumber.cs @@ -0,0 +1,78 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + using System; + + public partial class JsonNumber + { + internal static readonly DateTime EpochDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + private static long ToUnixTime(DateTime dateTime) + { + return (long)dateTime.Subtract(EpochDate).TotalSeconds; + } + private static DateTime FromUnixTime(long totalSeconds) + { + return EpochDate.AddSeconds(totalSeconds); + } + internal byte ToByte() => this; + internal int ToInt() => this; + internal long ToLong() => this; + internal short ToShort() => this; + internal UInt16 ToUInt16() => this; + internal UInt32 ToUInt32() => this; + internal UInt64 ToUInt64() => this; + internal decimal ToDecimal() => this; + internal double ToDouble() => this; + internal float ToFloat() => this; + + internal static JsonNumber Create(int? value) => value is int n ? new JsonNumber(n) : null; + internal static JsonNumber Create(long? value) => value is long n ? new JsonNumber(n) : null; + internal static JsonNumber Create(float? value) => value is float n ? new JsonNumber(n) : null; + internal static JsonNumber Create(double? value) => value is double n ? new JsonNumber(n) : null; + internal static JsonNumber Create(decimal? value) => value is decimal n ? new JsonNumber(n) : null; + internal static JsonNumber Create(DateTime? value) => value is DateTime date ? new JsonNumber(ToUnixTime(date)) : null; + + public static implicit operator DateTime(JsonNumber number) => FromUnixTime(number); + internal DateTime ToDateTime() => this; + + internal JsonNumber(decimal value) + { + this.value = value.ToString(); + } + internal override object ToValue() + { + if (IsInteger) + { + if (int.TryParse(this.value, out int iValue)) + { + return iValue; + } + if (long.TryParse(this.value, out long lValue)) + { + return lValue; + } + } + else + { + if (float.TryParse(this.value, out float fValue)) + { + return fValue; + } + if (double.TryParse(this.value, out double dValue)) + { + return dValue; + } + if (decimal.TryParse(this.value, out decimal dcValue)) + { + return dcValue; + } + } + return null; + } + } + + +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Customizations/JsonObject.cs b/src/AppConfiguration/generated/runtime/Customizations/JsonObject.cs new file mode 100644 index 000000000000..6816ddb0f4f1 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Customizations/JsonObject.cs @@ -0,0 +1,183 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + using System; + using System.Collections.Generic; + + public partial class JsonObject + { + internal override object ToValue() => Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.JsonSerializable.FromJson(this, new System.Collections.Generic.Dictionary(), (obj) => obj.ToValue()); + + internal void SafeAdd(string name, Func valueFn) + { + if (valueFn != null) + { + var value = valueFn(); + if (null != value) + { + items.Add(name, value); + } + } + } + + internal void SafeAdd(string name, JsonNode value) + { + if (null != value) + { + items.Add(name, value); + } + } + + internal T NullableProperty(string propertyName) where T : JsonNode + { + if (this.TryGetValue(propertyName, out JsonNode value)) + { + if (value.IsNull) + { + return null; + } + if (value is T tval) + { + return tval; + } + /* it's present, but not the correct type... */ + //throw new Exception($"Property {propertyName} in object expected type {typeof(T).Name} but value of type {value.Type.ToString()} was found."); + } + return null; + } + + internal JsonObject Property(string propertyName) + { + return PropertyT(propertyName); + } + + internal T PropertyT(string propertyName) where T : JsonNode + { + if (this.TryGetValue(propertyName, out JsonNode value)) + { + if (value.IsNull) + { + return null; // we're going to assume that the consumer knows what to do if null is explicity returned? + } + + if (value is T tval) + { + return tval; + } + /* it's present, but not the correct type... */ + // throw new Exception($"Property {propertyName} in object expected type {typeof(T).Name} but value of type {value.Type.ToString()} was found."); + } + return null; + } + + internal int NumberProperty(string propertyName, ref int output) => output = this.PropertyT(propertyName)?.ToInt() ?? output; + internal float NumberProperty(string propertyName, ref float output) => output = this.PropertyT(propertyName)?.ToFloat() ?? output; + internal byte NumberProperty(string propertyName, ref byte output) => output = this.PropertyT(propertyName)?.ToByte() ?? output; + internal long NumberProperty(string propertyName, ref long output) => output = this.PropertyT(propertyName)?.ToLong() ?? output; + internal double NumberProperty(string propertyName, ref double output) => output = this.PropertyT(propertyName)?.ToDouble() ?? output; + internal decimal NumberProperty(string propertyName, ref decimal output) => output = this.PropertyT(propertyName)?.ToDecimal() ?? output; + internal short NumberProperty(string propertyName, ref short output) => output = this.PropertyT(propertyName)?.ToShort() ?? output; + internal DateTime NumberProperty(string propertyName, ref DateTime output) => output = this.PropertyT(propertyName)?.ToDateTime() ?? output; + + internal int? NumberProperty(string propertyName, ref int? output) => output = this.NullableProperty(propertyName)?.ToInt() ?? null; + internal float? NumberProperty(string propertyName, ref float? output) => output = this.NullableProperty(propertyName)?.ToFloat() ?? null; + internal byte? NumberProperty(string propertyName, ref byte? output) => output = this.NullableProperty(propertyName)?.ToByte() ?? null; + internal long? NumberProperty(string propertyName, ref long? output) => output = this.NullableProperty(propertyName)?.ToLong() ?? null; + internal double? NumberProperty(string propertyName, ref double? output) => output = this.NullableProperty(propertyName)?.ToDouble() ?? null; + internal decimal? NumberProperty(string propertyName, ref decimal? output) => output = this.NullableProperty(propertyName)?.ToDecimal() ?? null; + internal short? NumberProperty(string propertyName, ref short? output) => output = this.NullableProperty(propertyName)?.ToShort() ?? null; + + internal DateTime? NumberProperty(string propertyName, ref DateTime? output) => output = this.NullableProperty(propertyName)?.ToDateTime() ?? null; + + + internal string StringProperty(string propertyName) => this.PropertyT(propertyName)?.ToString(); + internal string StringProperty(string propertyName, ref string output) => output = this.PropertyT(propertyName)?.ToString() ?? output; + internal char StringProperty(string propertyName, ref char output) => output = this.PropertyT(propertyName)?.ToChar() ?? output; + internal char? StringProperty(string propertyName, ref char? output) => output = this.PropertyT(propertyName)?.ToChar() ?? null; + + internal DateTime StringProperty(string propertyName, ref DateTime output) => DateTime.TryParse(this.PropertyT(propertyName)?.ToString(), out output) ? output : output; + internal DateTime? StringProperty(string propertyName, ref DateTime? output) => output = DateTime.TryParse(this.PropertyT(propertyName)?.ToString(), out var o) ? o : output; + + + internal bool BooleanProperty(string propertyName, ref bool output) => output = this.PropertyT(propertyName)?.ToBoolean() ?? output; + internal bool? BooleanProperty(string propertyName, ref bool? output) => output = this.PropertyT(propertyName)?.ToBoolean() ?? null; + + internal T[] ArrayProperty(string propertyName, ref T[] output, Func deserializer) + { + var array = this.PropertyT(propertyName); + if (array != null) + { + output = new T[array.Count]; + for (var i = 0; i < output.Length; i++) + { + output[i] = deserializer(array[i]); + } + } + return output; + } + internal T[] ArrayProperty(string propertyName, Func deserializer) + { + var array = this.PropertyT(propertyName); + if (array != null) + { + var output = new T[array.Count]; + for (var i = 0; i < output.Length; i++) + { + output[i] = deserializer(array[i]); + } + return output; + } + return new T[0]; + } + internal void IterateArrayProperty(string propertyName, Action deserializer) + { + var array = this.PropertyT(propertyName); + if (array != null) + { + for (var i = 0; i < array.Count; i++) + { + deserializer(array[i]); + } + } + } + + internal Dictionary DictionaryProperty(string propertyName, ref Dictionary output, Func deserializer) + { + var dictionary = this.PropertyT(propertyName); + if (output == null) + { + output = new Dictionary(); + } + else + { + output.Clear(); + } + if (dictionary != null) + { + foreach (var key in dictionary.Keys) + { + output[key] = deserializer(dictionary[key]); + } + } + return output; + } + + internal static JsonObject Create(IDictionary source, Func selector) + { + if (source == null || selector == null) + { + return null; + } + var result = new JsonObject(); + + foreach (var key in source.Keys) + { + result.SafeAdd(key, selector(source[key])); + } + return result; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Customizations/JsonString.cs b/src/AppConfiguration/generated/runtime/Customizations/JsonString.cs new file mode 100644 index 000000000000..60d8d77364ff --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Customizations/JsonString.cs @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + using System; + using System.Globalization; + using System.Linq; + + public partial class JsonString + { + internal static string DateFormat = "yyyy-MM-dd"; + internal static string DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; + internal static string DateTimeRfc1123Format = "R"; + + internal static JsonString Create(string value) => value == null ? null : new JsonString(value); + internal static JsonString Create(char? value) => value is char c ? new JsonString(c.ToString()) : null; + + internal static JsonString CreateDate(DateTime? value) => value is DateTime date ? new JsonString(date.ToString(DateFormat, CultureInfo.CurrentCulture)) : null; + internal static JsonString CreateDateTime(DateTime? value) => value is DateTime date ? new JsonString(date.ToString(DateTimeFormat, CultureInfo.CurrentCulture)) : null; + internal static JsonString CreateDateTimeRfc1123(DateTime? value) => value is DateTime date ? new JsonString(date.ToString(DateTimeRfc1123Format, CultureInfo.CurrentCulture)) : null; + + internal char ToChar() => this.Value?.ToString()?.FirstOrDefault() ?? default(char); + public static implicit operator char(JsonString value) => value?.ToString()?.FirstOrDefault() ?? default(char); + public static implicit operator char? (JsonString value) => value?.ToString()?.FirstOrDefault(); + + public static implicit operator DateTime(JsonString value) => DateTime.TryParse(value, out var output) ? output : default(DateTime); + public static implicit operator DateTime? (JsonString value) => DateTime.TryParse(value, out var output) ? output : default(DateTime?); + + } + + +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Customizations/XNodeArray.cs b/src/AppConfiguration/generated/runtime/Customizations/XNodeArray.cs new file mode 100644 index 000000000000..5be44b8cfd41 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Customizations/XNodeArray.cs @@ -0,0 +1,44 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + using System; + using System.Linq; + + public partial class XNodeArray + { + internal static XNodeArray Create(T[] source, Func selector) + { + if (source == null || selector == null) + { + return null; + } + var result = new XNodeArray(); + foreach (var item in source.Select(selector)) + { + result.SafeAdd(item); + } + return result; + } + internal void SafeAdd(JsonNode item) + { + if (item != null) + { + items.Add(item); + } + } + internal void SafeAdd(Func itemFn) + { + if (itemFn != null) + { + var item = itemFn(); + if (item != null) + { + items.Add(item); + } + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Debugging.cs b/src/AppConfiguration/generated/runtime/Debugging.cs new file mode 100644 index 000000000000..08ccf59ab857 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Debugging.cs @@ -0,0 +1,28 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + internal static class AttachDebugger + { + internal static void Break() + { + while (!System.Diagnostics.Debugger.IsAttached) + { + System.Console.Error.WriteLine($"Waiting for debugger to attach to process {System.Diagnostics.Process.GetCurrentProcess().Id}"); + for (int i = 0; i < 50; i++) + { + if (System.Diagnostics.Debugger.IsAttached) + { + break; + } + System.Threading.Thread.Sleep(100); + System.Console.Error.Write("."); + } + System.Console.Error.WriteLine(); + } + System.Diagnostics.Debugger.Break(); + } + } +} diff --git a/src/AppConfiguration/generated/runtime/DictionaryExtensions.cs b/src/AppConfiguration/generated/runtime/DictionaryExtensions.cs new file mode 100644 index 000000000000..b594fdcc73f0 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/DictionaryExtensions.cs @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + internal static class DictionaryExtensions + { + internal static void HashTableToDictionary(System.Collections.Hashtable hashtable, System.Collections.Generic.IDictionary dictionary) + { + foreach (var each in hashtable.Keys) + { + var key = each.ToString(); + var value = hashtable[key]; + if (null != value) + { + if (value is System.Collections.Hashtable nested) + { + HashTableToDictionary(nested, new System.Collections.Generic.Dictionary()); + } + else + { + try + { + dictionary[key] = (V)value; + } + catch + { + // Values getting dropped; not compatible with target dictionary. Not sure what to do here. + } + } + } + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/EventData.cs b/src/AppConfiguration/generated/runtime/EventData.cs new file mode 100644 index 000000000000..46c1a7edd6fd --- /dev/null +++ b/src/AppConfiguration/generated/runtime/EventData.cs @@ -0,0 +1,78 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + + using System; + using System.Threading; + + ///Represents the data in signaled event. + public partial class EventData + { + /// + /// The type of the event being signaled + /// + public string Id; + + /// + /// The user-ready message from the event. + /// + public string Message; + + /// + /// When the event is about a parameter, this is the parameter name. + /// Used in Validation Events + /// + public string Parameter; + + /// + /// This represents a numeric value associated with the event. + /// Use for progress-style events + /// + public double Value; + + /// + /// Any extended data for an event should be serialized and stored here. + /// + public string ExtendedData; + + /// + /// If the event triggers after the request message has been created, this will contain the Request Message (which in HTTP calls would be HttpRequestMessage) + /// + /// Typically you'd cast this to the expected type to use it: + /// + /// if(eventData.RequestMessgae is HttpRequestMessage httpRequest) + /// { + /// httpRequest.Headers.Add("x-request-flavor", "vanilla"); + /// } + /// + /// + public object RequestMessage; + + /// + /// If the event triggers after the response is back, this will contain the Response Message (which in HTTP calls would be HttpResponseMessage) + /// + /// Typically you'd cast this to the expected type to use it: + /// + /// if(eventData.ResponseMessage is HttpResponseMessage httpResponse){ + /// var flavor = httpResponse.Headers.GetValue("x-request-flavor"); + /// } + /// + /// + public object ResponseMessage; + + /// + /// Cancellation method for this event. + /// + /// If the event consumer wishes to cancel the request that initiated this event, call Cancel() + /// + /// + /// The original initiator of the request must provide the implementation of this. + /// + public System.Action Cancel; + } + +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/EventDataExtensions.cs b/src/AppConfiguration/generated/runtime/EventDataExtensions.cs new file mode 100644 index 000000000000..d8abbeaf3ab6 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/EventDataExtensions.cs @@ -0,0 +1,94 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + using System; + + [System.ComponentModel.TypeConverter(typeof(EventDataConverter))] + /// + /// PowerShell-specific data on top of the llc# EventData + /// + /// + /// In PowerShell, we add on the EventDataConverter to support sending events between modules. + /// Obviously, this code would need to be duplcated on both modules. + /// This is preferable to sharing a common library, as versioning makes that problematic. + /// + public partial class EventData : EventArgs + { + } + + /// + /// A PowerShell PSTypeConverter to adapt an EventData object that has been passed. + /// Usually used between modules. + /// + public class EventDataConverter : System.Management.Automation.PSTypeConverter + { + public override bool CanConvertTo(object sourceValue, Type destinationType) => false; + public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => null; + public override bool CanConvertFrom(dynamic sourceValue, Type destinationType) => destinationType == typeof(EventData) && CanConvertFrom(sourceValue); + public override object ConvertFrom(dynamic sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Verifies that a given object has the required members to convert it to the target type (EventData) + /// + /// Uses a dynamic type so that it is able to use the simplest code without excessive checking. + /// + /// The instance to verify + /// True, if the object has all the required parameters. + public static bool CanConvertFrom(dynamic sourceValue) + { + try + { + // check if this has *required* parameters... + sourceValue?.Id?.GetType(); + sourceValue?.Message?.GetType(); + sourceValue?.Cancel?.GetType(); + + // remaining parameters are not *required*, + // and if they have values, it will copy them at conversion time. + } + catch + { + // if anything throws an exception (because it's null, or doesn't have that member) + return false; + } + return true; + } + + /// + /// Returns result of the delegate as the expected type, or default(T) + /// + /// This isolates any exceptions from the consumer. + /// + /// A delegate that returns a value + /// The desired output type + /// The value from the function if the type is correct + private static T To(Func srcValue) + { + try { return srcValue(); } + catch { return default(T); } + } + + /// + /// Converts an incoming object to the expected type by treating the incoming object as a dynamic, and coping the expected values. + /// + /// the incoming object + /// EventData + public static EventData ConvertFrom(dynamic sourceValue) + { + return new EventData + { + Id = To(() => sourceValue.Id), + Message = To(() => sourceValue.Message), + Parameter = To(() => sourceValue.Parameter), + Value = To(() => sourceValue.Value), + RequestMessage = To(() => sourceValue.RequestMessage), + ResponseMessage = To(() => sourceValue.ResponseMessage), + Cancel = To(() => sourceValue.Cancel) + }; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/EventListener.cs b/src/AppConfiguration/generated/runtime/EventListener.cs new file mode 100644 index 000000000000..0539ed5a17da --- /dev/null +++ b/src/AppConfiguration/generated/runtime/EventListener.cs @@ -0,0 +1,247 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + + using System; + using System.Linq; + using System.Collections; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using GetEventData = System.Func; + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + public interface IValidates + { + Task Validate(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IEventListener listener); + } + + /// + /// The IEventListener Interface defines the communication mechanism for Signaling events during a remote call. + /// + /// + /// The interface is designed to be as minimal as possible, allow for quick peeking of the event type (id) + /// and the cancellation status and provides a delegate for retrieving the event details themselves. + /// + public interface IEventListener + { + Task Signal(string id, CancellationToken token, GetEventData createMessage); + CancellationToken Token { get; } + System.Action Cancel { get; } + } + + internal static partial class Extensions + { + public static Task Signal(this IEventListener instance, string id, CancellationToken token, Func createMessage) => instance.Signal(id, token, createMessage); + public static Task Signal(this IEventListener instance, string id, CancellationToken token) => instance.Signal(id, token, () => new EventData { Id = id, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, CancellationToken token, string messageText) => instance.Signal(id, token, () => new EventData { Id = id, Message = messageText, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, CancellationToken token, string messageText, HttpRequestMessage request) => instance.Signal(id, token, () => new EventData { Id = id, Message = messageText, RequestMessage = request, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, CancellationToken token, string messageText, HttpResponseMessage response) => instance.Signal(id, token, () => new EventData { Id = id, Message = messageText, RequestMessage = response.RequestMessage, ResponseMessage = response, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, CancellationToken token, string messageText, double magnitude) => instance.Signal(id, token, () => new EventData { Id = id, Message = messageText, Value = magnitude, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, CancellationToken token, string messageText, double magnitude, HttpRequestMessage request) => instance.Signal(id, token, () => new EventData { Id = id, Message = messageText, RequestMessage = request, Value = magnitude, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, CancellationToken token, string messageText, double magnitude, HttpResponseMessage response) => instance.Signal(id, token, () => new EventData { Id = id, Message = messageText, RequestMessage = response.RequestMessage, ResponseMessage = response, Value = magnitude, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, CancellationToken token, HttpRequestMessage request) => instance.Signal(id, token, () => new EventData { Id = id, RequestMessage = request, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, CancellationToken token, HttpRequestMessage request, HttpResponseMessage response) => instance.Signal(id, token, () => new EventData { Id = id, RequestMessage = request, ResponseMessage = response, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, CancellationToken token, HttpResponseMessage response) => instance.Signal(id, token, () => new EventData { Id = id, RequestMessage = response.RequestMessage, ResponseMessage = response, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, CancellationToken token, EventData message) => instance.Signal(id, token, () => { message.Id = id; message.Cancel = instance.Cancel; return message; }); + + public static Task Signal(this IEventListener instance, string id, Func createMessage) => instance.Signal(id, instance.Token, createMessage); + public static Task Signal(this IEventListener instance, string id) => instance.Signal(id, instance.Token, () => new EventData { Id = id, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, string messageText) => instance.Signal(id, instance.Token, () => new EventData { Id = id, Message = messageText, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, string messageText, HttpRequestMessage request) => instance.Signal(id, instance.Token, () => new EventData { Id = id, Message = messageText, RequestMessage = request, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, string messageText, HttpResponseMessage response) => instance.Signal(id, instance.Token, () => new EventData { Id = id, Message = messageText, RequestMessage = response.RequestMessage, ResponseMessage = response, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, string messageText, double magnitude) => instance.Signal(id, instance.Token, () => new EventData { Id = id, Message = messageText, Value = magnitude, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, string messageText, double magnitude, HttpRequestMessage request) => instance.Signal(id, instance.Token, () => new EventData { Id = id, Message = messageText, RequestMessage = request, Value = magnitude, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, string messageText, double magnitude, HttpResponseMessage response) => instance.Signal(id, instance.Token, () => new EventData { Id = id, Message = messageText, RequestMessage = response.RequestMessage, ResponseMessage = response, Value = magnitude, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, HttpRequestMessage request) => instance.Signal(id, instance.Token, () => new EventData { Id = id, RequestMessage = request, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, HttpRequestMessage request, HttpResponseMessage response) => instance.Signal(id, instance.Token, () => new EventData { Id = id, RequestMessage = request, ResponseMessage = response, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, HttpResponseMessage response) => instance.Signal(id, instance.Token, () => new EventData { Id = id, RequestMessage = response.RequestMessage, ResponseMessage = response, Cancel = instance.Cancel }); + public static Task Signal(this IEventListener instance, string id, EventData message) => instance.Signal(id, instance.Token, () => { message.Id = id; message.Cancel = instance.Cancel; return message; }); + + public static Task Signal(this IEventListener instance, string id, System.Uri uri) => instance.Signal(id, instance.Token, () => new EventData { Id = id, Message = uri.ToString(), Cancel = instance.Cancel }); + + public static async Task AssertNotNull(this IEventListener instance, string parameterName, object value) + { + if (value == null) + { + await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, Message = $"'{parameterName}' should not be null", Parameter = parameterName, Cancel = instance.Cancel }); + } + } + public static async Task AssertMinimumLength(this IEventListener instance, string parameterName, string value, int length) + { + if (value != null && value.Length < length) + { + await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, Message = $"Length of '{parameterName}' is less than {length}", Parameter = parameterName, Cancel = instance.Cancel }); + } + } + public static async Task AssertMaximumLength(this IEventListener instance, string parameterName, string value, int length) + { + if (value != null && value.Length > length) + { + await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, Message = $"Length of '{parameterName}' is greater than {length}", Parameter = parameterName, Cancel = instance.Cancel }); + } + } + + public static async Task AssertRegEx(this IEventListener instance, string parameterName, string value, string regularExpression) + { + if (value != null && !System.Text.RegularExpressions.Regex.Match(value, regularExpression).Success) + { + await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, Message = $"'{parameterName}' does not validate against pattern /{regularExpression}/", Parameter = parameterName, Cancel = instance.Cancel }); + } + } + public static async Task AssertEnum(this IEventListener instance, string parameterName, string value, params string[] values) + { + if (!values.Any(each => each.Equals(value))) + { + await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, Message = $"'{parameterName}' is not one of ({values.Aggregate((c, e) => $"'{e}',{c}")}", Parameter = parameterName, Cancel = instance.Cancel }); + } + } + public static async Task AssertObjectIsValid(this IEventListener instance, string parameterName, object inst) + { + await (inst as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.IValidates)?.Validate(instance); + } + + public static async Task AssertIsLessThan(this IEventListener instance, string parameterName, T? value, T max) where T : struct, System.IComparable + { + if (null != value && ((T)value).CompareTo(max) >= 0) + { + await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, Message = $"Value of '{parameterName}' must be less than {max} (value is {value})", Parameter = parameterName, Cancel = instance.Cancel }); + } + } + public static async Task AssertIsGreaterThan(this IEventListener instance, string parameterName, T? value, T max) where T : struct, System.IComparable + { + if (null != value && ((T)value).CompareTo(max) <= 0) + { + await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, Message = $"Value of '{parameterName}' must be greater than {max} (value is {value})", Parameter = parameterName, Cancel = instance.Cancel }); + } + } + public static async Task AssertIsLessThanOrEqual(this IEventListener instance, string parameterName, T? value, T max) where T : struct, System.IComparable + { + if (null != value && ((T)value).CompareTo(max) > 0) + { + await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, Message = $"Value of '{parameterName}' must be less than or equal to {max} (value is {value})", Parameter = parameterName, Cancel = instance.Cancel }); + } + } + public static async Task AssertIsGreaterThanOrEqual(this IEventListener instance, string parameterName, T? value, T max) where T : struct, System.IComparable + { + if (null != value && ((T)value).CompareTo(max) < 0) + { + await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, Message = $"Value of '{parameterName}' must be greater than or equal to {max} (value is {value})", Parameter = parameterName, Cancel = instance.Cancel }); + } + } + public static async Task AssertIsMultipleOf(this IEventListener instance, string parameterName, Int64? value, Int64 multiple) + { + if (null != value && value % multiple != 0) + { + await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, Message = $"Value of '{parameterName}' must be multiple of {multiple} (value is {value})", Parameter = parameterName, Cancel = instance.Cancel }); + } + } + public static async Task AssertIsMultipleOf(this IEventListener instance, string parameterName, double? value, double multiple) + { + if (null != value) + { + var i = (Int64)(value / multiple); + if (i != value / multiple) + { + await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, Message = $"Value of '{parameterName}' must be multiple of {multiple} (value is {value})", Parameter = parameterName, Cancel = instance.Cancel }); + } + } + } + public static async Task AssertIsMultipleOf(this IEventListener instance, string parameterName, decimal? value, decimal multiple) + { + if (null != value) + { + var i = (Int64)(value / multiple); + if (i != value / multiple) + { + await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Events.ValidationWarning, Message = $"Value of '{parameterName}' must be multiple of {multiple} (value is {value})", Parameter = parameterName, Cancel = instance.Cancel }); + } + } + } + } + + /// + /// An Implementation of the IEventListener that supports subscribing to events and dispatching them + /// (used for manually using the lowlevel interface) + /// + public class EventListener : CancellationTokenSource, IEnumerable>, IEventListener + { + private Dictionary calls = new Dictionary(); + public IEnumerator> GetEnumerator() => calls.GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => calls.GetEnumerator(); + public EventListener() + { + } + + public new Action Cancel => base.Cancel; + private Event tracer; + + public EventListener(params (string name, Event callback)[] initializer) + { + foreach (var each in initializer) + { + Add(each.name, each.callback); + } + } + + public void Add(string name, SynchEvent callback) + { + Add(name, (message) => { callback(message); return Task.CompletedTask; }); + } + + public void Add(string name, Event callback) + { + if (callback != null) + { + if (string.IsNullOrEmpty(name)) + { + if (calls.ContainsKey(name)) + { + tracer += callback; + } + else + { + tracer = callback; + } + } + else + { + if (calls.ContainsKey(name)) + { + calls[name ?? System.String.Empty] += callback; + } + else + { + calls[name ?? System.String.Empty] = callback; + } + } + } + } + + + public async Task Signal(string id, CancellationToken token, GetEventData createMessage) + { + using (NoSynchronizationContext) + { + if (!string.IsNullOrEmpty(id) && (calls.TryGetValue(id, out Event listener) || tracer != null)) + { + var message = createMessage(); + message.Id = id; + + await listener?.Invoke(message); + await tracer?.Invoke(message); + + if (token.IsCancellationRequested) + { + throw new OperationCanceledException($"Canceled by event {id} ", this.Token); + } + } + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Events.cs b/src/AppConfiguration/generated/runtime/Events.cs new file mode 100644 index 000000000000..53d10ff2a2a7 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Events.cs @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + public static partial class Events + { + public const string Log = nameof(Log); + public const string Validation = nameof(Validation); + public const string ValidationWarning = nameof(ValidationWarning); + public const string AfterValidation = nameof(AfterValidation); + public const string RequestCreated = nameof(RequestCreated); + public const string ResponseCreated = nameof(ResponseCreated); + public const string URLCreated = nameof(URLCreated); + public const string Finally = nameof(Finally); + public const string HeaderParametersAdded = nameof(HeaderParametersAdded); + public const string BodyContentSet = nameof(BodyContentSet); + public const string BeforeCall = nameof(BeforeCall); + public const string BeforeResponseDispatch = nameof(BeforeResponseDispatch); + public const string FollowingNextLink = nameof(FollowingNextLink); + public const string DelayBeforePolling = nameof(DelayBeforePolling); + public const string Polling = nameof(Polling); + + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/EventsExtensions.cs b/src/AppConfiguration/generated/runtime/EventsExtensions.cs new file mode 100644 index 000000000000..57f925255d1e --- /dev/null +++ b/src/AppConfiguration/generated/runtime/EventsExtensions.cs @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + public static partial class Events + { + public const string CmdletProcessRecordStart = nameof(CmdletProcessRecordStart); + public const string CmdletProcessRecordAsyncStart = nameof(CmdletProcessRecordAsyncStart); + public const string CmdletException = nameof(CmdletException); + public const string CmdletGetPipeline = nameof(CmdletGetPipeline); + public const string CmdletBeforeAPICall = nameof(CmdletBeforeAPICall); + public const string CmdletBeginProcessing = nameof(CmdletBeginProcessing); + public const string CmdletEndProcessing = nameof(CmdletEndProcessing); + public const string CmdletProcessRecordEnd = nameof(CmdletProcessRecordEnd); + public const string CmdletProcessRecordAsyncEnd = nameof(CmdletProcessRecordAsyncEnd); + public const string CmdletAfterAPICall = nameof(CmdletAfterAPICall); + + public const string Verbose = nameof(Verbose); + public const string Debug = nameof(Debug); + public const string Information = nameof(Information); + public const string Error = nameof(Error); + public const string Warning = nameof(Warning); + } + +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Extensions.cs b/src/AppConfiguration/generated/runtime/Extensions.cs new file mode 100644 index 000000000000..c41cdb37266d --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Extensions.cs @@ -0,0 +1,111 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + using System.Linq; + + internal static partial class Extensions + { + + public static T ReadHeaders(this T instance, global::System.Net.Http.Headers.HttpResponseHeaders headers) where T : class + { + (instance as IHeaderSerializable)?.ReadHeaders(headers); + return instance; + } + + internal static bool If(T input, out T output) + { + if (null == input) + { + output = default(T); + return false; + } + output = input; + return true; + } + + internal static void AddIf(T value, System.Action addMethod) + { + // if value is present (and it's not just an empty JSON Object) + if (null != value && (value as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject)?.Keys.Count != 0) + { + addMethod(value); + } + } + + internal static void AddIf(T value, string serializedName, System.Action addMethod) + { + // if value is present (and it's not just an empty JSON Object) + if (null != value && (value as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject)?.Keys.Count != 0) + { + addMethod(serializedName, value); + } + } + + /// + /// Returns the first header value as a string from an HttpReponseMessage. + /// + /// the HttpResponseMessage to fetch a header from + /// the header name + /// the first header value as a string from an HttpReponseMessage. string.empty if there is no header value matching + internal static string GetFirstHeader(this System.Net.Http.HttpResponseMessage response, string headerName) => response.Headers.FirstOrDefault(each => headerName == each.Key).Value?.FirstOrDefault() ?? string.Empty; + + /// + /// Sets the Synchronization Context to null, and returns an IDisposable that when disposed, + /// will restore the synchonization context to the original value. + /// + /// This is used a less-invasive means to ensure that code in the library that doesn't + /// need to be continued in the original context doesn't have to have ConfigureAwait(false) + /// on every single await + /// + /// If the SynchronizationContext is null when this is used, the resulting IDisposable + /// will not do anything (this prevents excessive re-setting of the SynchronizationContext) + /// + /// Usage: + /// + /// using(NoSynchronizationContext) { + /// await SomeAsyncOperation(); + /// await SomeOtherOperation(); + /// } + /// + /// + /// + /// An IDisposable that will return the SynchronizationContext to original state + internal static System.IDisposable NoSynchronizationContext => System.Threading.SynchronizationContext.Current == null ? Dummy : new NoSyncContext(); + + /// + /// An instance of the Dummy IDispoable. + /// + /// + internal static System.IDisposable Dummy = new DummyDisposable(); + + /// + /// An IDisposable that does absolutely nothing. + /// + internal class DummyDisposable : System.IDisposable + { + public void Dispose() + { + } + } + /// + /// An IDisposable that saves the SynchronizationContext,sets it to null and + /// restores it to the original upon Dispose(). + /// + /// NOTE: This is designed to be less invasive than using .ConfigureAwait(false) + /// on every single await in library code (ie, places where we know we don't need + /// to continue in the same context as we went async) + /// + internal class NoSyncContext : System.IDisposable + { + private System.Threading.SynchronizationContext original = System.Threading.SynchronizationContext.Current; + internal NoSyncContext() + { + System.Threading.SynchronizationContext.SetSynchronizationContext(null); + } + public void Dispose() => System.Threading.SynchronizationContext.SetSynchronizationContext(original); + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs b/src/AppConfiguration/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs new file mode 100644 index 000000000000..9e1b76a860e7 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs @@ -0,0 +1,23 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Text; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal static class StringBuilderExtensions + { + /// + /// Extracts the buffered value and resets the buffer + /// + internal static string Extract(this StringBuilder builder) + { + var text = builder.ToString(); + + builder.Clear(); + + return text; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Helpers/Extensions/TypeExtensions.cs b/src/AppConfiguration/generated/runtime/Helpers/Extensions/TypeExtensions.cs new file mode 100644 index 000000000000..66287239b515 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Helpers/Extensions/TypeExtensions.cs @@ -0,0 +1,61 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal static class TypeExtensions + { + internal static bool IsNullable(this Type type) => + type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)); + + internal static Type GetOpenGenericInterface(this Type candidateType, Type openGenericInterfaceType) + { + + if (candidateType.IsGenericType && candidateType.GetGenericTypeDefinition() == openGenericInterfaceType) + { + return candidateType; + } + + // Check if it references it's own converter.... + + foreach (Type interfaceType in candidateType.GetInterfaces()) + { + if (interfaceType.IsGenericType + && interfaceType.GetGenericTypeDefinition().Equals(openGenericInterfaceType)) + { + return interfaceType; + } + } + + return null; + } + + // Author: Sebastian Good + // http://stackoverflow.com/questions/503263/how-to-determine-if-a-type-implements-a-specific-generic-interface-type + internal static bool ImplementsOpenGenericInterface(this Type candidateType, Type openGenericInterfaceType) + { + if (candidateType.Equals(openGenericInterfaceType)) + { + return true; + } + + if (candidateType.IsGenericType && candidateType.GetGenericTypeDefinition().Equals(openGenericInterfaceType)) + { + return true; + } + + foreach (Type i in candidateType.GetInterfaces()) + { + if (i.IsGenericType && i.ImplementsOpenGenericInterface(openGenericInterfaceType)) + { + return true; + } + } + + return false; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Helpers/Seperator.cs b/src/AppConfiguration/generated/runtime/Helpers/Seperator.cs new file mode 100644 index 000000000000..803c78347840 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Helpers/Seperator.cs @@ -0,0 +1,11 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal static class Seperator + { + internal static readonly char[] Dash = { '-' }; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Helpers/TypeDetails.cs b/src/AppConfiguration/generated/runtime/Helpers/TypeDetails.cs new file mode 100644 index 000000000000..24cdc3212d38 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Helpers/TypeDetails.cs @@ -0,0 +1,116 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + + + + internal class TypeDetails + { + private readonly Type info; + + internal TypeDetails(Type info) + { + this.info = info ?? throw new ArgumentNullException(nameof(info)); + } + + internal Type NonNullType { get; set; } + + internal object DefaultValue { get; set; } + + internal bool IsNullable { get; set; } + + internal bool IsList { get; set; } + + internal bool IsStringLike { get; set; } + + internal bool IsEnum => info.IsEnum; + + internal bool IsArray => info.IsArray; + + internal bool IsValueType => info.IsValueType; + + internal Type ElementType { get; set; } + + internal IJsonConverter JsonConverter { get; set; } + + #region Creation + + private static readonly ConcurrentDictionary cache = new ConcurrentDictionary(); + + internal static TypeDetails Get() => Get(typeof(T)); + + internal static TypeDetails Get(Type type) => cache.GetOrAdd(type, Create); + + private static TypeDetails Create(Type type) + { + var isGenericList = !type.IsPrimitive && type.ImplementsOpenGenericInterface(typeof(IList<>)); + var isList = !type.IsPrimitive && (isGenericList || typeof(IList).IsAssignableFrom(type)); + + var isNullable = type.IsNullable(); + + Type elementType; + + if (type.IsArray) + { + elementType = type.GetElementType(); + } + else if (isGenericList) + { + var iList = type.GetOpenGenericInterface(typeof(IList<>)); + + elementType = iList.GetGenericArguments()[0]; + } + else + { + elementType = null; + } + + var nonNullType = isNullable ? type.GetGenericArguments()[0] : type; + + var isStringLike = false; + + IJsonConverter converter; + + var jsonConverterAttribute = type.GetCustomAttribute(); + + if (jsonConverterAttribute != null) + { + converter = jsonConverterAttribute.Converter; + } + else if (nonNullType.IsEnum) + { + converter = new EnumConverter(nonNullType); + } + else if (JsonConverterFactory.Instances.TryGetValue(nonNullType, out converter)) + { + } + else if (StringLikeHelper.IsStringLike(nonNullType)) + { + isStringLike = true; + + converter = new StringLikeConverter(nonNullType); + } + + return new TypeDetails(nonNullType) { + NonNullType = nonNullType, + DefaultValue = type.IsValueType ? Activator.CreateInstance(type) : null, + IsNullable = isNullable, + IsList = isList, + IsStringLike = isStringLike, + ElementType = elementType, + JsonConverter = converter + }; + } + + #endregion + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Helpers/XHelper.cs b/src/AppConfiguration/generated/runtime/Helpers/XHelper.cs new file mode 100644 index 000000000000..203b3164ec7f --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Helpers/XHelper.cs @@ -0,0 +1,75 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal static class XHelper + { + internal static JsonNode Create(JsonType type, TypeCode code, object value) + { + switch (type) + { + case JsonType.Binary : return new XBinary((byte[])value); + case JsonType.Boolean : return new JsonBoolean((bool)value); + case JsonType.Number : return new JsonNumber(value.ToString()); + case JsonType.String : return new JsonString((string)value); + } + + throw new Exception($"JsonType '{type}' does not have a fast conversion"); + } + + internal static bool TryGetElementType(TypeCode code, out JsonType type) + { + switch (code) + { + case TypeCode.Boolean : type = JsonType.Boolean; return true; + case TypeCode.Byte : type = JsonType.Number; return true; + case TypeCode.DateTime : type = JsonType.Date; return true; + case TypeCode.Decimal : type = JsonType.Number; return true; + case TypeCode.Double : type = JsonType.Number; return true; + case TypeCode.Empty : type = JsonType.Null; return true; + case TypeCode.Int16 : type = JsonType.Number; return true; + case TypeCode.Int32 : type = JsonType.Number; return true; + case TypeCode.Int64 : type = JsonType.Number; return true; + case TypeCode.SByte : type = JsonType.Number; return true; + case TypeCode.Single : type = JsonType.Number; return true; + case TypeCode.String : type = JsonType.String; return true; + case TypeCode.UInt16 : type = JsonType.Number; return true; + case TypeCode.UInt32 : type = JsonType.Number; return true; + case TypeCode.UInt64 : type = JsonType.Number; return true; + } + + type = default; + + return false; + } + + internal static JsonType GetElementType(TypeCode code) + { + switch (code) + { + case TypeCode.Boolean : return JsonType.Boolean; + case TypeCode.Byte : return JsonType.Number; + case TypeCode.DateTime : return JsonType.Date; + case TypeCode.Decimal : return JsonType.Number; + case TypeCode.Double : return JsonType.Number; + case TypeCode.Empty : return JsonType.Null; + case TypeCode.Int16 : return JsonType.Number; + case TypeCode.Int32 : return JsonType.Number; + case TypeCode.Int64 : return JsonType.Number; + case TypeCode.SByte : return JsonType.Number; + case TypeCode.Single : return JsonType.Number; + case TypeCode.String : return JsonType.String; + case TypeCode.UInt16 : return JsonType.Number; + case TypeCode.UInt32 : return JsonType.Number; + case TypeCode.UInt64 : return JsonType.Number; + default : return JsonType.Object; + } + + throw new Exception($"TypeCode '{code}' does not have a fast converter"); + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/HttpPipeline.cs b/src/AppConfiguration/generated/runtime/HttpPipeline.cs new file mode 100644 index 000000000000..bdf5da9a90d8 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/HttpPipeline.cs @@ -0,0 +1,88 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + using System.Net.Http; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using System.Collections; + using System.Linq; + + using GetEventData = System.Func; + using NextDelegate = System.Func, System.Threading.Tasks.Task>, System.Threading.Tasks.Task>; + + using SignalDelegate = System.Func, System.Threading.Tasks.Task>; + using GetParameterDelegate = System.Func, string, object>; + using SendAsyncStepDelegate = System.Func, System.Threading.Tasks.Task>, System.Func, System.Threading.Tasks.Task>, System.Threading.Tasks.Task>, System.Threading.Tasks.Task>; + using PipelineChangeDelegate = System.Action, System.Threading.Tasks.Task>, System.Func, System.Threading.Tasks.Task>, System.Threading.Tasks.Task>, System.Threading.Tasks.Task>>; + using ModuleLoadPipelineDelegate = System.Action, System.Threading.Tasks.Task>, System.Func, System.Threading.Tasks.Task>, System.Threading.Tasks.Task>, System.Threading.Tasks.Task>>, System.Action, System.Threading.Tasks.Task>, System.Func, System.Threading.Tasks.Task>, System.Threading.Tasks.Task>, System.Threading.Tasks.Task>>>; + using NewRequestPipelineDelegate = System.Action, System.Action, System.Threading.Tasks.Task>, System.Func, System.Threading.Tasks.Task>, System.Threading.Tasks.Task>, System.Threading.Tasks.Task>>, System.Action, System.Threading.Tasks.Task>, System.Func, System.Threading.Tasks.Task>, System.Threading.Tasks.Task>, System.Threading.Tasks.Task>>>; + +/* + public class DelegateBasedEventListener : IEventListener + { + private EventListenerDelegate _listener; + public DelegateBasedEventListener(EventListenerDelegate listener) + { + _listener = listener; + } + public CancellationToken Token => CancellationToken.None; + public System.Action Cancel => () => { }; + + + public Task Signal(string id, CancellationToken token, GetEventData createMessage) + { + return _listener(id, token, () => createMessage()); + } + } +*/ + /// + /// This is a necessary extension to the SendAsyncFactory to support the 'generic' delegate format. + /// + public partial class SendAsyncFactory + { + /// + /// This translates a generic-defined delegate for a listener into one that fits our ISendAsync pattern. + /// (Provided to support out-of-module delgation for Azure Cmdlets) + /// + /// The Pipeline Step as a delegate + public SendAsyncFactory(SendAsyncStepDelegate step) => this.implementation = (request, listener, next) => + step( + request, + listener.Token, + listener.Cancel, + (id, token, getEventData) => listener.Signal(id, token, () => { + var data = EventDataConverter.ConvertFrom( getEventData() ) as EventData; + data.Id = id; + data.Cancel = listener.Cancel; + data.RequestMessage = request; + return data; + }), + (req, token, cancel, listenerDelegate) => next.SendAsync(req, listener)); + } + + public partial class HttpPipeline : ISendAsync + { + public HttpPipeline Append(SendAsyncStepDelegate item) + { + if (item != null) + { + Append(new SendAsyncFactory(item)); + } + return this; + } + + public HttpPipeline Prepend(SendAsyncStepDelegate item) + { + if (item != null) + { + Prepend(new SendAsyncFactory(item)); + } + return this; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/HttpPipelineMocking.ps1 b/src/AppConfiguration/generated/runtime/HttpPipelineMocking.ps1 new file mode 100644 index 000000000000..7ec4b72e7ebb --- /dev/null +++ b/src/AppConfiguration/generated/runtime/HttpPipelineMocking.ps1 @@ -0,0 +1,110 @@ +$ErrorActionPreference = "Stop" + +# get the recording path +if (-not $TestRecordingFile) { + $TestRecordingFile = Join-Path $PSScriptRoot 'recording.json' +} + +# create the Http Pipeline Recorder +$Mock = New-Object -Type Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PipelineMock $TestRecordingFile + +# set the recorder to the appropriate mode (default to 'live') +Write-Host -ForegroundColor Green "Running '$TestMode' mode..." +switch ($TestMode) { + 'record' { + Write-Host -ForegroundColor Green "Recording to $TestRecordingFile" + $Mock.SetRecord() + $null = erase -ea 0 $TestRecordingFile + } + 'playback' { + if (-not (Test-Path $TestRecordingFile)) { + Write-Host -fore:yellow "Recording file '$TestRecordingFile' is not present. Tests expecting recorded responses will fail" + } else { + Write-Host -ForegroundColor Green "Using recording $TestRecordingFile" + } + $Mock.SetPlayback() + $Mock.ForceResponseHeaders["Retry-After"] = "0"; + } + default: { + $Mock.SetLive() + } +} + +# overrides for Pester Describe/Context/It + +function Describe( + [Parameter(Mandatory = $true, Position = 0)] + [string] $Name, + + [Alias('Tags')] + [string[]] $Tag = @(), + + [Parameter(Position = 1)] + [ValidateNotNull()] + [ScriptBlock] $Fixture = $(Throw "No test script block is provided. (Have you put the open curly brace on the next line?)") +) { + $Mock.PushDescription($Name) + try { + return pester\Describe -Name $Name -Tag $Tag -Fixture $fixture + } + finally { + $Mock.PopDescription() + } +} + +function Context( + [Parameter(Mandatory = $true, Position = 0)] + [string] $Name, + + [Alias('Tags')] + [string[]] $Tag = @(), + + [Parameter(Position = 1)] + [ValidateNotNull()] + [ScriptBlock] $Fixture = $(Throw "No test script block is provided. (Have you put the open curly brace on the next line?)") +) { + $Mock.PushContext($Name) + try { + return pester\Context -Name $Name -Tag $Tag -Fixture $fixture + } + finally { + $Mock.PopContext() + } +} + +function It { + [CmdletBinding(DefaultParameterSetName = 'Normal')] + param( + [Parameter(Mandatory = $true, Position = 0)] + [string]$Name, + + [Parameter(Position = 1)] + [ScriptBlock] $Test = { }, + + [System.Collections.IDictionary[]] $TestCases, + + [Parameter(ParameterSetName = 'Pending')] + [Switch] $Pending, + + [Parameter(ParameterSetName = 'Skip')] + [Alias('Ignore')] + [Switch] $Skip + ) + $Mock.PushScenario($Name) + + try { + if ($skip) { + return pester\It -Name $Name -Test $Test -TestCases $TestCases -Skip + } + if ($pending) { + return pester\It -Name $Name -Test $Test -TestCases $TestCases -Pending + } + return pester\It -Name $Name -Test $Test -TestCases $TestCases + } + finally { + $null = $Mock.PopScenario() + } +} + +# set the HttpPipelineAppend for all the cmdlets +$PSDefaultParameterValues["*:HttpPipelinePrepend"] = $Mock diff --git a/src/AppConfiguration/generated/runtime/IAssociativeArray.cs b/src/AppConfiguration/generated/runtime/IAssociativeArray.cs new file mode 100644 index 000000000000..728889f5db72 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/IAssociativeArray.cs @@ -0,0 +1,21 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + /// A subset of IDictionary that doesn't implement IEnumerable or IDictionary to work around PowerShell's aggressive formatter + public interface IAssociativeArray + { + System.Collections.Generic.IEnumerable Keys { get; } + System.Collections.Generic.IEnumerable Values { get; } + System.Collections.Generic.IDictionary AdditionalProperties { get; } + T this[string index] { get; set; } + int Count { get; } + void Add(string key, T value); + bool ContainsKey(string key); + bool Remove(string key); + bool TryGetValue(string key, out T value); + void Clear(); + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/IHeaderSerializable.cs b/src/AppConfiguration/generated/runtime/IHeaderSerializable.cs new file mode 100644 index 000000000000..273de045d6cd --- /dev/null +++ b/src/AppConfiguration/generated/runtime/IHeaderSerializable.cs @@ -0,0 +1,14 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + public interface IHeaderSerializable + { + void ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers); + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/ISendAsync.cs b/src/AppConfiguration/generated/runtime/ISendAsync.cs new file mode 100644 index 000000000000..643a5aa895f2 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/ISendAsync.cs @@ -0,0 +1,289 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + using System.Net.Http; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using System.Collections; + using System.Linq; + + /// + /// The interface for sending an HTTP request across the wire. + /// + public interface ISendAsync + { + Task SendAsync(HttpRequestMessage request, IEventListener callback); + } + + public class SendAsyncTerminalFactory : ISendAsyncTerminalFactory, ISendAsync + { + SendAsync implementation; + + public SendAsyncTerminalFactory(SendAsync implementation) => this.implementation = implementation; + public SendAsyncTerminalFactory(ISendAsync implementation) => this.implementation = implementation.SendAsync; + public ISendAsync Create() => this; + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback); + } + + public partial class SendAsyncFactory : ISendAsyncFactory + { + public class Sender : ISendAsync + { + internal ISendAsync next; + internal SendAsyncStep implementation; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback, next); + } + SendAsyncStep implementation; + + public SendAsyncFactory(SendAsyncStep implementation) => this.implementation = implementation; + public ISendAsync Create(ISendAsync next) => new Sender { next = next, implementation = implementation }; + + } + + public class HttpClientFactory : ISendAsyncTerminalFactory, ISendAsync + { + HttpClient client; + public HttpClientFactory() : this(new HttpClient()) + { + } + public HttpClientFactory(HttpClient client) => this.client = client; + public ISendAsync Create() => this; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, callback.Token); + } + + public interface ISendAsyncFactory + { + ISendAsync Create(ISendAsync next); + } + + public interface ISendAsyncTerminalFactory + { + ISendAsync Create(); + } + + public partial class HttpPipeline : ISendAsync + { + private ISendAsync pipeline; + private ISendAsyncTerminalFactory terminal; + private List steps = new List(); + + public HttpPipeline() : this(new HttpClientFactory()) + { + } + + public HttpPipeline(ISendAsyncTerminalFactory terminalStep) + { + if (terminalStep == null) + { + throw new System.ArgumentNullException(nameof(terminalStep), "Terminal Step Factory in HttpPipeline may not be null"); + } + TerminalFactory = terminalStep; + } + + /// + /// Returns an HttpPipeline with the current state of this pipeline. + /// + public HttpPipeline Clone() => new HttpPipeline(terminal) { steps = this.steps.ToList(), pipeline = this.pipeline }; + + public ISendAsyncTerminalFactory TerminalFactory + { + get => terminal; + set + { + if (value == null) + { + throw new System.ArgumentNullException("TerminalFactory in HttpPipeline may not be null"); + } + terminal = value; + } + } + + public ISendAsync Pipeline + { + get + { + // if the pipeline has been created and not invalidated, return it. + if (this.pipeline != null) + { + return this.pipeline; + } + + // create the pipeline from scratch. + var next = terminal.Create(); + foreach (var factory in steps) + { + // skip factories that return null. + next = factory.Create(next) ?? next; + } + return this.pipeline = next; + } + } + + public int Count => steps.Count; + + public HttpPipeline Prepend(ISendAsyncFactory item) + { + if (item != null) + { + steps.Add(item); + pipeline = null; + } + return this; + } + + public HttpPipeline Append(SendAsyncStep item) + { + if (item != null) + { + Append(new SendAsyncFactory(item)); + } + return this; + } + + public HttpPipeline Prepend(SendAsyncStep item) + { + if (item != null) + { + Prepend(new SendAsyncFactory(item)); + } + return this; + } + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Append(ISendAsyncFactory item) + { + if (item != null) + { + steps.Insert(0, item); + pipeline = null; + } + return this; + } + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(item); + } + } + return this; + } + + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(item); + } + } + return this; + } + + // you can use this as the ISendAsync Implementation + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => Pipeline.SendAsync(request, callback); + } + + internal static partial class Extensions + { + internal static HttpRequestMessage CloneAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.Clone(requestUri, method); + } + } + + internal static Task CloneWithContentAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.CloneWithContent(requestUri, method); + } + } + + /// + /// Clones an HttpRequestMessage (without the content) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// A clone of the HttpRequestMessage + internal static HttpRequestMessage Clone(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = new HttpRequestMessage + { + Method = method ?? original.Method, + RequestUri = requestUri ?? original.RequestUri, + Version = original.Version, + }; + + foreach (KeyValuePair prop in original.Properties) + { + clone.Properties.Add(prop); + } + + foreach (KeyValuePair> header in original.Headers) + { + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); + } + + return clone; + } + + /// + /// Clones an HttpRequestMessage (including the content stream and content headers) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// A clone of the HttpRequestMessage + internal static async Task CloneWithContent(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = original.Clone(requestUri, method); + var stream = new System.IO.MemoryStream(); + if (original.Content != null) + { + await original.Content.CopyToAsync(stream).ConfigureAwait(false); + stream.Position = 0; + clone.Content = new StreamContent(stream); + if (original.Content.Headers != null) + { + foreach (var h in original.Content.Headers) + { + clone.Content.Headers.Add(h.Key, h.Value); + } + } + } + return clone; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/InfoAttribute.cs b/src/AppConfiguration/generated/runtime/InfoAttribute.cs new file mode 100644 index 000000000000..db9c040db1fb --- /dev/null +++ b/src/AppConfiguration/generated/runtime/InfoAttribute.cs @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + using System; + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Class)] + public class InfoAttribute : Attribute + { + public bool Required { get; set; } = false; + public bool ReadOnly { get; set; } = false; + public Type[] PossibleTypes { get; set; } = new Type[0]; + public string Description { get; set; } = ""; + public string SerializedName { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class CompleterInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class DefaultInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Iso/IsoDate.cs b/src/AppConfiguration/generated/runtime/Iso/IsoDate.cs new file mode 100644 index 000000000000..7b6437384750 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Iso/IsoDate.cs @@ -0,0 +1,214 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Text; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal struct IsoDate + { + internal int Year { get; set; } // 0-3000 + + internal int Month { get; set; } // 1-12 + + internal int Day { get; set; } // 1-31 + + internal int Hour { get; set; } // 0-24 + + internal int Minute { get; set; } // 0-60 (60 is a special case) + + internal int Second { get; set; } // 0-60 (60 is used for leap seconds) + + internal double Millisecond { get; set; } // 0-999.9... + + internal TimeSpan Offset { get; set; } + + internal DateTimeKind Kind { get; set; } + + internal TimeSpan TimeOfDay => new TimeSpan(Hour, Minute, Second); + + internal DateTime ToDateTime() + { + if (Kind == DateTimeKind.Utc || Offset == TimeSpan.Zero) + { + return new DateTime(Year, Month, Day, Hour, Minute, Second, (int)Millisecond, DateTimeKind.Utc); + } + + return ToDateTimeOffset().DateTime; + } + + internal DateTimeOffset ToDateTimeOffset() + { + return new DateTimeOffset( + Year, + Month, + Day, + Hour, + Minute, + Second, + (int)Millisecond, + Offset + ); + } + + internal DateTime ToUtcDateTime() + { + return ToDateTimeOffset().UtcDateTime; + } + + public override string ToString() + { + var sb = new StringBuilder(); + + // yyyy-MM-dd + sb.Append($"{Year}-{Month:00}-{Day:00}"); + + if (TimeOfDay > new TimeSpan(0)) + { + sb.Append($"T{Hour:00}:{Minute:00}"); + + if (TimeOfDay.Seconds > 0) + { + sb.Append($":{Second:00}"); + } + } + + if (Offset.Ticks == 0) + { + sb.Append('Z'); // UTC + } + else + { + if (Offset.Ticks >= 0) + { + sb.Append('+'); + } + + sb.Append($"{Offset.Hours:00}:{Offset.Minutes:00}"); + } + + return sb.ToString(); + } + + internal static IsoDate FromDateTimeOffset(DateTimeOffset date) + { + return new IsoDate { + Year = date.Year, + Month = date.Month, + Day = date.Day, + Hour = date.Hour, + Minute = date.Minute, + Second = date.Second, + Offset = date.Offset, + Kind = date.Offset == TimeSpan.Zero ? DateTimeKind.Utc : DateTimeKind.Unspecified + }; + } + + private static readonly char[] timeSeperators = { ':', '.' }; + + internal static IsoDate Parse(string text) + { + var tzIndex = -1; + var timeIndex = text.IndexOf('T'); + + var builder = new IsoDate { Day = 1, Month = 1 }; + + // TODO: strip the time zone offset off the end + string dateTime = text; + string timeZone = null; + + if (dateTime.IndexOf('Z') > -1) + { + tzIndex = dateTime.LastIndexOf('Z'); + + builder.Kind = DateTimeKind.Utc; + } + else if (dateTime.LastIndexOf('+') > 10) + { + tzIndex = dateTime.LastIndexOf('+'); + } + else if (dateTime.LastIndexOf('-') > 10) + { + tzIndex = dateTime.LastIndexOf('-'); + } + + if (tzIndex > -1) + { + timeZone = dateTime.Substring(tzIndex); + dateTime = dateTime.Substring(0, tzIndex); + } + + string date = (timeIndex == -1) ? dateTime : dateTime.Substring(0, timeIndex); + + var dateParts = date.Split(Seperator.Dash); // '-' + + for (int i = 0; i < dateParts.Length; i++) + { + var part = dateParts[i]; + + switch (i) + { + case 0: builder.Year = int.Parse(part); break; + case 1: builder.Month = int.Parse(part); break; + case 2: builder.Day = int.Parse(part); break; + } + } + + if (timeIndex > -1) + { + string[] timeParts = dateTime.Substring(timeIndex + 1).Split(timeSeperators); + + for (int i = 0; i < timeParts.Length; i++) + { + var part = timeParts[i]; + + switch (i) + { + case 0: builder.Hour = int.Parse(part); break; + case 1: builder.Minute = int.Parse(part); break; + case 2: builder.Second = int.Parse(part); break; + case 3: builder.Millisecond = double.Parse("0." + part) * 1000; break; + } + } + } + + if (timeZone != null && timeZone != "Z") + { + var hours = int.Parse(timeZone.Substring(1, 2)); + var minutes = int.Parse(timeZone.Substring(4, 2)); + + if (timeZone[0] == '-') + { + hours = -hours; + minutes = -minutes; + } + + builder.Offset = new TimeSpan(hours, minutes, 0); + } + + return builder; + } + } + + /* + YYYY # eg 1997 + YYYY-MM # eg 1997-07 + YYYY-MM-DD # eg 1997-07-16 + YYYY-MM-DDThh:mmTZD # eg 1997-07-16T19:20+01:00 + YYYY-MM-DDThh:mm:ssTZD # eg 1997-07-16T19:20:30+01:00 + YYYY-MM-DDThh:mm:ss.sTZD # eg 1997-07-16T19:20:30.45+01:00 + + where: + + YYYY = four-digit year + MM = two-digit month (01=January, etc.) + DD = two-digit day of month (01 through 31) + hh = two digits of hour (00 through 23) (am/pm NOT allowed) + mm = two digits of minute (00 through 59) + ss = two digits of second (00 through 59) + s = one or more digits representing a decimal fraction of a second + TZD = time zone designator (Z or +hh:mm or -hh:mm) + */ +} diff --git a/src/AppConfiguration/generated/runtime/JsonType.cs b/src/AppConfiguration/generated/runtime/JsonType.cs new file mode 100644 index 000000000000..e37f6290a3a7 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/JsonType.cs @@ -0,0 +1,18 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal enum JsonType + { + Null = 0, + Object = 1, + Array = 2, + Binary = 3, + Boolean = 4, + Date = 5, + Number = 6, + String = 7 + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Method.cs b/src/AppConfiguration/generated/runtime/Method.cs new file mode 100644 index 000000000000..4ab8c6e09f8d --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Method.cs @@ -0,0 +1,19 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + internal static class Method + { + internal static System.Net.Http.HttpMethod Get = System.Net.Http.HttpMethod.Get; + internal static System.Net.Http.HttpMethod Put = System.Net.Http.HttpMethod.Put; + internal static System.Net.Http.HttpMethod Head = System.Net.Http.HttpMethod.Head; + internal static System.Net.Http.HttpMethod Post = System.Net.Http.HttpMethod.Post; + internal static System.Net.Http.HttpMethod Delete = System.Net.Http.HttpMethod.Delete; + internal static System.Net.Http.HttpMethod Options = System.Net.Http.HttpMethod.Options; + internal static System.Net.Http.HttpMethod Trace = System.Net.Http.HttpMethod.Trace; + internal static System.Net.Http.HttpMethod Patch = new System.Net.Http.HttpMethod("PATCH"); + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Models/JsonMember.cs b/src/AppConfiguration/generated/runtime/Models/JsonMember.cs new file mode 100644 index 000000000000..2f0603f705f3 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Models/JsonMember.cs @@ -0,0 +1,83 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Reflection; +using System.Runtime.Serialization; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + + + internal sealed class JsonMember + { + private readonly TypeDetails type; + + private readonly Func getter; + private readonly Action setter; + + internal JsonMember(PropertyInfo property, int defaultOrder) + { + getter = property.GetValue; + setter = property.SetValue; + + var dataMember = property.GetCustomAttribute(); + + Name = dataMember?.Name ?? property.Name; + Order = dataMember?.Order ?? defaultOrder; + EmitDefaultValue = dataMember?.EmitDefaultValue ?? true; + + this.type = TypeDetails.Get(property.PropertyType); + + CanRead = property.CanRead; + } + + internal JsonMember(FieldInfo field, int defaultOrder) + { + getter = field.GetValue; + setter = field.SetValue; + + var dataMember = field.GetCustomAttribute(); + + Name = dataMember?.Name ?? field.Name; + Order = dataMember?.Order ?? defaultOrder; + EmitDefaultValue = dataMember?.EmitDefaultValue ?? true; + + this.type = TypeDetails.Get(field.FieldType); + + CanRead = true; + } + + internal string Name { get; } + + internal int Order { get; } + + internal TypeDetails TypeDetails => type; + + internal Type Type => type.NonNullType; + + internal bool IsList => type.IsList; + + // Arrays, Sets, ... + internal Type ElementType => type.ElementType; + + internal IJsonConverter Converter => type.JsonConverter; + + internal bool EmitDefaultValue { get; } + + internal bool IsStringLike => type.IsStringLike; + + internal object DefaultValue => type.DefaultValue; + + internal bool CanRead { get; } + + #region Helpers + + internal object GetValue(object instance) => getter(instance); + + internal void SetValue(object instance, object value) => setter(instance, value); + + #endregion + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Models/JsonModel.cs b/src/AppConfiguration/generated/runtime/Models/JsonModel.cs new file mode 100644 index 000000000000..34026b904911 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Models/JsonModel.cs @@ -0,0 +1,89 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal class JsonModel + { + private Dictionary map; + private readonly object _sync = new object(); + + private JsonModel(Type type, List members) + { + Type = type ?? throw new ArgumentNullException(nameof(type)); + Members = members ?? throw new ArgumentNullException(nameof(members)); + } + + internal string Name => Type.Name; + + internal Type Type { get; } + + internal List Members { get; } + + internal JsonMember this[string name] + { + get + { + if (map == null) + { + lock (_sync) + { + if (map == null) + { + map = new Dictionary(); + + foreach (JsonMember m in Members) + { + map[m.Name.ToLower()] = m; + } + } + } + } + + + map.TryGetValue(name.ToLower(), out JsonMember member); + + return member; + } + } + + internal static JsonModel FromType(Type type) + { + var members = new List(); + + int i = 0; + + // BindingFlags.Instance | BindingFlags.Public + + foreach (var member in type.GetFields()) + { + if (member.IsStatic) continue; + + if (member.IsDefined(typeof(IgnoreDataMemberAttribute))) continue; + + members.Add(new JsonMember(member, i)); + + i++; + } + + foreach (var member in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + if (member.IsDefined(typeof(IgnoreDataMemberAttribute))) continue; + + members.Add(new JsonMember(member, i)); + + i++; + } + + members.Sort((a, b) => a.Order.CompareTo(b.Order)); // inline sort + + return new JsonModel(type, members); + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Models/JsonModelCache.cs b/src/AppConfiguration/generated/runtime/Models/JsonModelCache.cs new file mode 100644 index 000000000000..623afb8646b4 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Models/JsonModelCache.cs @@ -0,0 +1,19 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Runtime.CompilerServices; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal static class JsonModelCache + { + private static readonly ConditionalWeakTable cache + = new ConditionalWeakTable(); + + internal static JsonModel Get(Type type) => cache.GetValue(type, Create); + + private static JsonModel Create(Type type) => JsonModel.FromType(type); + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Nodes/Collections/JsonArray.cs b/src/AppConfiguration/generated/runtime/Nodes/Collections/JsonArray.cs new file mode 100644 index 000000000000..64a29ba4a388 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Nodes/Collections/JsonArray.cs @@ -0,0 +1,65 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public abstract partial class JsonArray : JsonNode, IEnumerable + { + internal override JsonType Type => JsonType.Array; + + internal abstract JsonType? ElementType { get; } + + public abstract int Count { get; } + + internal virtual bool IsSet => false; + + internal bool IsEmpty => Count == 0; + + #region IEnumerable + + IEnumerator IEnumerable.GetEnumerator() + { + throw new NotImplementedException(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + throw new NotImplementedException(); + } + + #endregion + + #region Static Helpers + + internal static JsonArray Create(short[] values) + => new XImmutableArray(values); + + internal static JsonArray Create(int[] values) + => new XImmutableArray(values); + + internal static JsonArray Create(long[] values) + => new XImmutableArray(values); + + internal static JsonArray Create(decimal[] values) + => new XImmutableArray(values); + + internal static JsonArray Create(float[] values) + => new XImmutableArray(values); + + internal static JsonArray Create(string[] values) + => new XImmutableArray(values); + + internal static JsonArray Create(XBinary[] values) + => new XImmutableArray(values); + + #endregion + + internal static new JsonArray Parse(string text) + => (JsonArray)JsonNode.Parse(text); + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Nodes/Collections/XImmutableArray.cs b/src/AppConfiguration/generated/runtime/Nodes/Collections/XImmutableArray.cs new file mode 100644 index 000000000000..fcde4e701bb4 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Nodes/Collections/XImmutableArray.cs @@ -0,0 +1,62 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal sealed class XImmutableArray : JsonArray, IEnumerable + { + private readonly T[] values; + private readonly JsonType elementType; + private readonly TypeCode elementCode; + + internal XImmutableArray(T[] values) + { + this.values = values ?? throw new ArgumentNullException(nameof(values)); + this.elementCode = System.Type.GetTypeCode(typeof(T)); + this.elementType = XHelper.GetElementType(this.elementCode); + } + + public override JsonNode this[int index] => + XHelper.Create(elementType, elementCode, values[index]); + + internal override JsonType? ElementType => elementType; + + public override int Count => values.Length; + + public bool IsReadOnly => true; + + #region IEnumerable Members + + IEnumerator IEnumerable.GetEnumerator() + { + foreach (T value in values) + { + yield return XHelper.Create(elementType, elementCode, value); + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + foreach (T value in values) + { + yield return XHelper.Create(elementType, elementCode, value); + } + } + + #endregion + + #region Static Constructor + + internal XImmutableArray Create(T[] items) + { + return new XImmutableArray(items); + } + + #endregion + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Nodes/Collections/XList.cs b/src/AppConfiguration/generated/runtime/Nodes/Collections/XList.cs new file mode 100644 index 000000000000..529e4d6d2239 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Nodes/Collections/XList.cs @@ -0,0 +1,64 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal sealed class XList : JsonArray, IEnumerable + { + private readonly IList values; + private readonly JsonType elementType; + private readonly TypeCode elementCode; + + internal XList(IList values) + { + this.values = values ?? throw new ArgumentNullException(nameof(values)); + this.elementCode = System.Type.GetTypeCode(typeof(T)); + this.elementType = XHelper.GetElementType(this.elementCode); + } + + public override JsonNode this[int index] => + XHelper.Create(elementType, elementCode, values[index]); + + internal override JsonType? ElementType => elementType; + + public override int Count => values.Count; + + public bool IsReadOnly => values.IsReadOnly; + + #region IList + + public void Add(T value) + { + values.Add(value); + } + + public bool Contains(T value) => values.Contains(value); + + #endregion + + #region IEnumerable Members + + IEnumerator IEnumerable.GetEnumerator() + { + foreach (var value in values) + { + yield return XHelper.Create(elementType, elementCode, value); + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + foreach (var value in values) + { + yield return XHelper.Create(elementType, elementCode, value); + } + } + + #endregion + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Nodes/Collections/XNodeArray.cs b/src/AppConfiguration/generated/runtime/Nodes/Collections/XNodeArray.cs new file mode 100644 index 000000000000..2ceb80fedcfa --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Nodes/Collections/XNodeArray.cs @@ -0,0 +1,68 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed partial class XNodeArray : JsonArray, ICollection + { + private readonly List items; + + internal XNodeArray() + { + items = new List(); + } + + internal XNodeArray(params JsonNode[] values) + { + items = new List(values); + } + + public override JsonNode this[int index] => items[index]; + + internal override JsonType? ElementType => null; + + public bool IsReadOnly => false; + + public override int Count => items.Count; + + #region ICollection Members + + public void Add(JsonNode item) + { + items.Add(item); + } + + void ICollection.Clear() + { + items.Clear(); + } + + public bool Contains(JsonNode item) => items.Contains(item); + + void ICollection.CopyTo(JsonNode[] array, int arrayIndex) + { + items.CopyTo(array, arrayIndex); + } + + public bool Remove(JsonNode item) + { + return items.Remove(item); + } + + #endregion + + #region IEnumerable Members + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + #endregion + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Nodes/Collections/XSet.cs b/src/AppConfiguration/generated/runtime/Nodes/Collections/XSet.cs new file mode 100644 index 000000000000..6ecc25828a14 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Nodes/Collections/XSet.cs @@ -0,0 +1,60 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal sealed class XSet : JsonArray, IEnumerable + { + private readonly HashSet values; + private readonly JsonType elementType; + private readonly TypeCode elementCode; + + internal XSet(IEnumerable values) + : this(new HashSet(values)) + { } + + internal XSet(HashSet values) + { + this.values = values ?? throw new ArgumentNullException(nameof(values)); + this.elementCode = System.Type.GetTypeCode(typeof(T)); + this.elementType = XHelper.GetElementType(this.elementCode); + } + + internal override JsonType Type => JsonType.Array; + + internal override JsonType? ElementType => elementType; + + public bool IsReadOnly => true; + + public override int Count => values.Count; + + internal override bool IsSet => true; + + #region IEnumerable Members + + IEnumerator IEnumerable.GetEnumerator() + { + foreach (var value in values) + { + yield return XHelper.Create(elementType, elementCode, value); + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + foreach (var value in values) + { + yield return XHelper.Create(elementType, elementCode, value); + } + } + + #endregion + + internal HashSet AsHashSet() => values; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Nodes/JsonBoolean.cs b/src/AppConfiguration/generated/runtime/Nodes/JsonBoolean.cs new file mode 100644 index 000000000000..7796ca9827a3 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Nodes/JsonBoolean.cs @@ -0,0 +1,42 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal sealed partial class JsonBoolean : JsonNode + { + internal static readonly JsonBoolean True = new JsonBoolean(true); + internal static readonly JsonBoolean False = new JsonBoolean(false); + + internal JsonBoolean(bool value) + { + Value = value; + } + + internal bool Value { get; } + + internal override JsonType Type => JsonType.Boolean; + + internal static new JsonBoolean Parse(string text) + { + switch (text) + { + case "false": return False; + case "true": return True; + + default: throw new ArgumentException($"Expected true or false. Was {text}."); + } + } + + #region Implicit Casts + + public static implicit operator bool(JsonBoolean data) => data.Value; + + public static implicit operator JsonBoolean(bool data) => new JsonBoolean(data); + + #endregion + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Nodes/JsonDate.cs b/src/AppConfiguration/generated/runtime/Nodes/JsonDate.cs new file mode 100644 index 000000000000..8950b95371d2 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Nodes/JsonDate.cs @@ -0,0 +1,173 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + + + internal sealed partial class JsonDate : JsonNode, IEquatable, IComparable + { + internal static bool AssumeUtcWhenKindIsUnspecified = true; + + private readonly DateTimeOffset value; + + internal JsonDate(DateTime value) + { + if (value.Kind == DateTimeKind.Unspecified && AssumeUtcWhenKindIsUnspecified) + { + value = DateTime.SpecifyKind(value, DateTimeKind.Utc); + } + + this.value = value; + } + + internal JsonDate(DateTimeOffset value) + { + this.value = value; + } + + internal override JsonType Type => JsonType.Date; + + #region Helpers + + internal DateTimeOffset ToDateTimeOffset() + { + return value; + } + + internal DateTime ToDateTime() + { + if (value.Offset == TimeSpan.Zero) + { + return value.UtcDateTime; + } + + return value.DateTime; + } + + internal DateTime ToUtcDateTime() => value.UtcDateTime; + + internal int ToUnixTimeSeconds() + { + return (int)value.ToUnixTimeSeconds(); + } + + internal long ToUnixTimeMilliseconds() + { + return (int)value.ToUnixTimeMilliseconds(); + } + + internal string ToIsoString() + { + return IsoDate.FromDateTimeOffset(value).ToString(); + } + + #endregion + + public override string ToString() + { + return ToIsoString(); + } + + internal static new JsonDate Parse(string text) + { + if (text == null) throw new ArgumentNullException(nameof(text)); + + // TODO support: unixtimeseconds.partialseconds + + if (text.Length > 4 && _IsNumber(text)) // UnixTime + { + var date = DateTimeOffset.FromUnixTimeSeconds(long.Parse(text)); + + return new JsonDate(date); + } + else if (text.Length <= 4 || text[4] == '-') // ISO: 2012- + { + return new JsonDate(IsoDate.Parse(text).ToDateTimeOffset()); + } + else + { + // NOT ISO ENCODED + // "Thu, 5 Apr 2012 16:59:01 +0200", + return new JsonDate(DateTimeOffset.Parse(text)); + } + } + + private static bool _IsNumber(string text) + { + foreach (var c in text) + { + if (!char.IsDigit(c)) return false; + } + + return true; + } + + internal static JsonDate FromUnixTime(int seconds) + { + return new JsonDate(DateTimeOffset.FromUnixTimeSeconds(seconds)); + } + + internal static JsonDate FromUnixTime(double seconds) + { + var milliseconds = (long)(seconds * 1000d); + + return new JsonDate(DateTimeOffset.FromUnixTimeMilliseconds(milliseconds)); + } + + #region Implicit Casts + + public static implicit operator DateTimeOffset(JsonDate value) + => value.ToDateTimeOffset(); + + public static implicit operator DateTime(JsonDate value) + => value.ToDateTime(); + + // From Date + public static implicit operator JsonDate(DateTimeOffset value) + { + return new JsonDate(value); + } + + public static implicit operator JsonDate(DateTime value) + { + return new JsonDate(value); + } + + // From String + public static implicit operator JsonDate(string value) + { + return Parse(value); + } + + #endregion + + #region Equality + + public override bool Equals(object obj) + { + return obj is JsonDate date && date.value == this.value; + } + + public bool Equals(JsonDate other) + { + return this.value == other.value; + } + + public override int GetHashCode() => value.GetHashCode(); + + #endregion + + #region IComparable Members + + int IComparable.CompareTo(JsonDate other) + { + return value.CompareTo(other.value); + } + + #endregion + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Nodes/JsonNode.cs b/src/AppConfiguration/generated/runtime/Nodes/JsonNode.cs new file mode 100644 index 000000000000..199f98054958 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Nodes/JsonNode.cs @@ -0,0 +1,250 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Text; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + + + public abstract partial class JsonNode + { + internal abstract JsonType Type { get; } + + public virtual JsonNode this[int index] => throw new NotImplementedException(); + + public virtual JsonNode this[string name] + { + get => throw new NotImplementedException(); + set => throw new NotImplementedException(); + } + + #region Type Helpers + + internal bool IsArray => Type == JsonType.Array; + + internal bool IsDate => Type == JsonType.Date; + + internal bool IsObject => Type == JsonType.Object; + + internal bool IsNumber => Type == JsonType.Number; + + internal bool IsNull => Type == JsonType.Null; + + #endregion + + internal void WriteTo(TextWriter textWriter, bool pretty = true) + { + var writer = new JsonWriter(textWriter, pretty); + + writer.WriteNode(this); + } + + internal T As() + where T : new() + => new JsonSerializer().Deseralize((JsonObject)this); + + internal T[] ToArrayOf() + { + return (T[])new JsonSerializer().DeserializeArray(typeof(T[]), (JsonArray)this); + } + + #region ToString Overrides + + public override string ToString() => ToString(pretty: true); + + internal string ToString(bool pretty) + { + var sb = new StringBuilder(); + + using (var writer = new StringWriter(sb)) + { + WriteTo(writer, pretty); + + return sb.ToString(); + } + } + + #endregion + + #region Static Constructors + + internal static JsonNode Parse(string text) + { + return Parse(new SourceReader(new StringReader(text))); + } + + internal static JsonNode Parse(TextReader textReader) + => Parse(new SourceReader(textReader)); + + private static JsonNode Parse(SourceReader sourceReader) + { + using (var parser = new JsonParser(sourceReader)) + { + return parser.ReadNode(); + } + } + + internal static JsonNode FromObject(object instance) + => new JsonSerializer().Serialize(instance); + + #endregion + + #region Implict Casts + + public static implicit operator string(JsonNode node) => node.ToString(); + + #endregion + + #region Explict Casts + + public static explicit operator DateTime(JsonNode node) + { + switch (node.Type) + { + case JsonType.Date: + return ((JsonDate)node).ToDateTime(); + + case JsonType.String: + return JsonDate.Parse(node.ToString()).ToDateTime(); + + case JsonType.Number: + var num = (JsonNumber)node; + + if (num.IsInteger) + { + return DateTimeOffset.FromUnixTimeSeconds(num).UtcDateTime; + } + else + { + return DateTimeOffset.FromUnixTimeMilliseconds((long)((double)num * 1000)).UtcDateTime; + } + } + + throw new ConversionException(node, typeof(DateTime)); + } + + public static explicit operator DateTimeOffset(JsonNode node) + { + switch (node.Type) + { + case JsonType.Date : return ((JsonDate)node).ToDateTimeOffset(); + case JsonType.String : return JsonDate.Parse(node.ToString()).ToDateTimeOffset(); + + case JsonType.Number: + var num = (JsonNumber)node; + + if (num.IsInteger) + { + return DateTimeOffset.FromUnixTimeSeconds(num); + } + else + { + return DateTimeOffset.FromUnixTimeMilliseconds((long)((double)num * 1000)); + } + + } + + throw new ConversionException(node, typeof(DateTimeOffset)); + } + + public static explicit operator float(JsonNode node) + { + switch (node.Type) + { + case JsonType.Number : return (JsonNumber)node; + case JsonType.String : return float.Parse(node.ToString()); + } + + throw new ConversionException(node, typeof(float)); + } + + public static explicit operator double(JsonNode node) + { + switch (node.Type) + { + case JsonType.Number : return (JsonNumber)node; + case JsonType.String : return double.Parse(node.ToString()); + } + + throw new ConversionException(node, typeof(double)); + } + + public static explicit operator decimal(JsonNode node) + { + switch (node.Type) + { + case JsonType.Number: return (JsonNumber)node; + case JsonType.String: return decimal.Parse(node.ToString()); + } + + throw new ConversionException(node, typeof(decimal)); + } + + public static explicit operator Guid(JsonNode node) + => new Guid(node.ToString()); + + public static explicit operator short(JsonNode node) + { + switch (node.Type) + { + case JsonType.Number : return (JsonNumber)node; + case JsonType.String : return short.Parse(node.ToString()); + } + + throw new ConversionException(node, typeof(short)); + } + + public static explicit operator int(JsonNode node) + { + switch (node.Type) + { + case JsonType.Number : return (JsonNumber)node; + case JsonType.String : return int.Parse(node.ToString()); + } + + throw new ConversionException(node, typeof(int)); + } + + public static explicit operator long(JsonNode node) + { + switch (node.Type) + { + case JsonType.Number: return (JsonNumber)node; + case JsonType.String: return long.Parse(node.ToString()); + } + + throw new ConversionException(node, typeof(long)); + } + + public static explicit operator bool(JsonNode node) + => ((JsonBoolean)node).Value; + + public static explicit operator ushort(JsonNode node) + => (JsonNumber)node; + + public static explicit operator uint(JsonNode node) + => (JsonNumber)node; + + public static explicit operator ulong(JsonNode node) + => (JsonNumber)node; + + public static explicit operator TimeSpan(JsonNode node) + => TimeSpan.Parse(node.ToString()); + + public static explicit operator Uri(JsonNode node) + { + if (node.Type == JsonType.String) + { + return new Uri(node.ToString()); + } + + throw new ConversionException(node, typeof(Uri)); + } + + #endregion + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Nodes/JsonNumber.cs b/src/AppConfiguration/generated/runtime/Nodes/JsonNumber.cs new file mode 100644 index 000000000000..c004ece18a41 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Nodes/JsonNumber.cs @@ -0,0 +1,109 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed partial class JsonNumber : JsonNode + { + private readonly string value; + private readonly bool overflows = false; + + internal JsonNumber(string value) + { + this.value = value ?? throw new ArgumentNullException(nameof(value)); + } + + internal JsonNumber(int value) + { + this.value = value.ToString(); + } + + internal JsonNumber(long value) + { + this.value = value.ToString(); + + if (value > 9007199254740991) + { + overflows = true; + } + } + + internal JsonNumber(float value) + { + this.value = value.ToString(); + } + + internal JsonNumber(double value) + { + this.value = value.ToString(); + } + + internal override JsonType Type => JsonType.Number; + + internal string Value => value; + + #region Helpers + + internal bool Overflows => overflows; + + internal bool IsInteger => !value.Contains("."); + + internal bool IsFloat => value.Contains("."); + + #endregion + + #region Casting + + public static implicit operator byte(JsonNumber number) + => byte.Parse(number.Value); + + public static implicit operator short(JsonNumber number) + => short.Parse(number.Value); + + public static implicit operator int(JsonNumber number) + => int.Parse(number.Value); + + public static implicit operator long(JsonNumber number) + => long.Parse(number.value); + + public static implicit operator UInt16(JsonNumber number) + => ushort.Parse(number.Value); + + public static implicit operator UInt32(JsonNumber number) + => uint.Parse(number.Value); + + public static implicit operator UInt64(JsonNumber number) + => ulong.Parse(number.Value); + + public static implicit operator decimal(JsonNumber number) + => decimal.Parse(number.Value); + + public static implicit operator Double(JsonNumber number) + => double.Parse(number.value); + + public static implicit operator float(JsonNumber number) + => float.Parse(number.value); + + public static implicit operator JsonNumber(short data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(int data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(long data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(Single data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(double data) + => new JsonNumber(data.ToString()); + + #endregion + + public override string ToString() => value; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Nodes/JsonObject.cs b/src/AppConfiguration/generated/runtime/Nodes/JsonObject.cs new file mode 100644 index 000000000000..c6373f661058 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Nodes/JsonObject.cs @@ -0,0 +1,172 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public partial class JsonObject : JsonNode, IDictionary + { + private readonly Dictionary items; + + internal JsonObject() + { + items = new Dictionary(); + } + + internal JsonObject(IEnumerable> properties) + { + if (properties == null) throw new ArgumentNullException(nameof(properties)); + + items = new Dictionary(); + + foreach (var field in properties) + { + items.Add(field.Key, field.Value); + } + } + + #region IDictionary Constructors + + internal JsonObject(IDictionary dic) + { + items = new Dictionary(dic.Count); + + foreach (var pair in dic) + { + Add(pair.Key, pair.Value); + } + } + + #endregion + + internal override JsonType Type => JsonType.Object; + + #region Add Overloads + + public void Add(string name, JsonNode value) => + items.Add(name, value); + + public void Add(string name, byte[] value) => + items.Add(name, new XBinary(value)); + + public void Add(string name, DateTime value) => + items.Add(name, new JsonDate(value)); + + public void Add(string name, int value) => + items.Add(name, new JsonNumber(value.ToString())); + + public void Add(string name, long value) => + items.Add(name, new JsonNumber(value.ToString())); + + public void Add(string name, float value) => + items.Add(name, new JsonNumber(value.ToString())); + + public void Add(string name, double value) => + items.Add(name, new JsonNumber(value.ToString())); + + public void Add(string name, string value) => + items.Add(name, new JsonString(value)); + + public void Add(string name, bool value) => + items.Add(name, new JsonBoolean(value)); + + public void Add(string name, Uri url) => + items.Add(name, new JsonString(url.AbsoluteUri)); + + public void Add(string name, string[] values) => + items.Add(name, new XImmutableArray(values)); + + public void Add(string name, int[] values) => + items.Add(name, new XImmutableArray(values)); + + #endregion + + #region ICollection> Members + + void ICollection>.Add(KeyValuePair item) + { + items.Add(item.Key, item.Value); + } + + void ICollection>.Clear() + { + items.Clear(); + } + + bool ICollection>.Contains(KeyValuePair item) => + throw new NotImplementedException(); + + void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) => + throw new NotImplementedException(); + + + int ICollection>.Count => items.Count; + + bool ICollection>.IsReadOnly => false; + + bool ICollection>.Remove(KeyValuePair item) => + throw new NotImplementedException(); + + #endregion + + #region IDictionary Members + + public bool ContainsKey(string key) => items.ContainsKey(key); + + public ICollection Keys => items.Keys; + + public bool Remove(string key) => items.Remove(key); + + public bool TryGetValue(string key, out JsonNode value) => + items.TryGetValue(key, out value); + + public ICollection Values => items.Values; + + public override JsonNode this[string key] + { + get => items[key]; + set => items[key] = value; + } + + #endregion + + #region IEnumerable + + IEnumerator> IEnumerable>.GetEnumerator() + => items.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + #endregion + + #region Helpers + + internal static new JsonObject FromObject(object instance) => + (JsonObject)new JsonSerializer().Serialize(instance); + + #endregion + + #region Static Constructors + + internal static JsonObject FromStream(Stream stream) + { + using (var tr = new StreamReader(stream)) + { + return (JsonObject)Parse(tr); + } + } + + internal static new JsonObject Parse(string text) + { + return (JsonObject)JsonNode.Parse(text); + } + + #endregion + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Nodes/JsonString.cs b/src/AppConfiguration/generated/runtime/Nodes/JsonString.cs new file mode 100644 index 000000000000..4768feaf77e7 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Nodes/JsonString.cs @@ -0,0 +1,42 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed partial class JsonString : JsonNode, IEquatable + { + private readonly string value; + + internal JsonString(string value) + { + this.value = value ?? throw new ArgumentNullException(nameof(value)); + } + + internal override JsonType Type => JsonType.String; + + internal string Value => value; + + internal int Length => value.Length; + + #region #region Implicit Casts + + public static implicit operator string(JsonString data) => data.Value; + + public static implicit operator JsonString(string value) => new JsonString(value); + + #endregion + + public override int GetHashCode() => value.GetHashCode(); + + public override string ToString() => value; + + #region IEquatable + + bool IEquatable.Equals(JsonString other) => this.Value == other.Value; + + #endregion + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Nodes/XBinary.cs b/src/AppConfiguration/generated/runtime/Nodes/XBinary.cs new file mode 100644 index 000000000000..4587196d0871 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Nodes/XBinary.cs @@ -0,0 +1,40 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal sealed class XBinary : JsonNode + { + private readonly byte[] _value; + private readonly string _base64; + + internal XBinary(byte[] value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + internal XBinary(string base64EncodedString) + { + _base64 = base64EncodedString ?? throw new ArgumentNullException(nameof(base64EncodedString)); + } + + internal override JsonType Type => JsonType.Binary; + + internal byte[] Value => _value ?? Convert.FromBase64String(_base64); + + #region #region Implicit Casts + + public static implicit operator byte[] (XBinary data) => data.Value; + + public static implicit operator XBinary(byte[] data) => new XBinary(data); + + #endregion + + public override int GetHashCode() => Value.GetHashCode(); + + public override string ToString() => _base64 ?? Convert.ToBase64String(_value); + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Nodes/XNull.cs b/src/AppConfiguration/generated/runtime/Nodes/XNull.cs new file mode 100644 index 000000000000..b0c6857dd4d2 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Nodes/XNull.cs @@ -0,0 +1,15 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal sealed class XNull : JsonNode + { + internal static readonly XNull Instance = new XNull(); + + private XNull() { } + + internal override JsonType Type => JsonType.Null; + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Parser/Exceptions/ParseException.cs b/src/AppConfiguration/generated/runtime/Parser/Exceptions/ParseException.cs new file mode 100644 index 000000000000..72d49730956e --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Parser/Exceptions/ParseException.cs @@ -0,0 +1,24 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal class ParserException : Exception + { + internal ParserException(string message) + : base(message) + { } + + internal ParserException(string message, SourceLocation location) + : base(message) + { + + Location = location; + } + + internal SourceLocation Location { get; } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Parser/JsonParser.cs b/src/AppConfiguration/generated/runtime/Parser/JsonParser.cs new file mode 100644 index 000000000000..44e796a6a5c3 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Parser/JsonParser.cs @@ -0,0 +1,180 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public class JsonParser : IDisposable + { + private readonly TokenReader reader; + + internal JsonParser(TextReader reader) + : this(new SourceReader(reader)) { } + + internal JsonParser(SourceReader sourceReader) + { + if (sourceReader == null) + throw new ArgumentNullException(nameof(sourceReader)); + + this.reader = new TokenReader(new JsonTokenizer(sourceReader)); + + this.reader.Next(); // Start with the first token + } + + internal IEnumerable ReadNodes() + { + JsonNode node; + + while ((node = ReadNode()) != null) yield return node; + } + + internal JsonNode ReadNode() + { + if (reader.Current.Kind == TokenKind.Eof || reader.Current.IsTerminator) + { + return null; + } + + switch (reader.Current.Kind) + { + case TokenKind.LeftBrace : return ReadObject(); // { + case TokenKind.LeftBracket : return ReadArray(); // [ + + default: throw new ParserException($"Expected '{{' or '['. Was {reader.Current}."); + } + } + + private JsonNode ReadFieldValue() + { + // Boolean, Date, Null, Number, String, Uri + if (reader.Current.IsLiteral) + { + return ReadLiteral(); + } + else + { + switch (reader.Current.Kind) + { + case TokenKind.LeftBracket: return ReadArray(); + case TokenKind.LeftBrace : return ReadObject(); + + default: throw new ParserException($"Unexpected token reading field value. Was {reader.Current}."); + } + } + } + + private JsonNode ReadLiteral() + { + var literal = reader.Current; + + reader.Next(); // Read the literal token + + switch (literal.Kind) + { + case TokenKind.Boolean : return JsonBoolean.Parse(literal.Value); + case TokenKind.Null : return XNull.Instance; + case TokenKind.Number : return new JsonNumber(literal.Value); + case TokenKind.String : return new JsonString(literal.Value); + + default: throw new ParserException($"Unexpected token reading literal. Was {literal}."); + } + } + + internal JsonObject ReadObject() + { + reader.Ensure(TokenKind.LeftBrace, "object"); + + reader.Next(); // Read '{' (Object start) + + var jsonObject = new JsonObject(); + + // Read the object's fields until we reach the end of the object ('}') + while (reader.Current.Kind != TokenKind.RightBrace) + { + if (reader.Current.Kind == TokenKind.Comma) + { + reader.Next(); // Read ',' (Seperator) + } + + // Ensure we have a field name + reader.Ensure(TokenKind.String, "Expected field name"); + + var field = ReadField(); + + jsonObject.Add(field.Key, field.Value); + } + + reader.Next(); // Read '}' (Object end) + + return jsonObject; + } + + + // TODO: Use ValueTuple in C#7 + private KeyValuePair ReadField() + { + var fieldName = reader.Current.Value; + + reader.Next(); // Read the field name + + reader.Ensure(TokenKind.Colon, "field"); + + reader.Next(); // Read ':' (Field value indicator) + + return new KeyValuePair(fieldName, ReadFieldValue()); + } + + + internal JsonArray ReadArray() + { + reader.Ensure(TokenKind.LeftBracket, "array"); + + var array = new XNodeArray(); + + reader.Next(); // Read the '[' (Array start) + + // Read the array's items + while (reader.Current.Kind != TokenKind.RightBracket) + { + if (reader.Current.Kind == TokenKind.Comma) + { + reader.Next(); // Read the ',' (Seperator) + } + + if (reader.Current.IsLiteral) + { + array.Add(ReadLiteral()); // Boolean, Date, Number, Null, String, Uri + } + else if (reader.Current.Kind == TokenKind.LeftBracket) + { + array.Add(ReadArray()); // Array + } + else if (reader.Current.Kind == TokenKind.LeftBrace) + { + array.Add(ReadObject()); // Object + } + else + { + throw new ParserException($"Expected comma, literal, or object. Was {reader.Current}."); + } + } + + reader.Next(); // Read the ']' (Array end) + + return array; + } + + #region IDisposable + + public void Dispose() + { + reader.Dispose(); + } + + #endregion + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Parser/JsonToken.cs b/src/AppConfiguration/generated/runtime/Parser/JsonToken.cs new file mode 100644 index 000000000000..a2e3c7f58423 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Parser/JsonToken.cs @@ -0,0 +1,66 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal enum TokenKind + { + LeftBrace, // { Object start + RightBrace, // } Object end + + LeftBracket, // [ Array start + RightBracket, // ] Array end + + Comma, // , Comma + Colon, // : Value indicator + Dot, // . Access field indicator + Terminator, // \0 Stream terminator + + Boolean = 31, // true or false + Null = 33, // null + Number = 34, // i.e. -1.93, -1, 0, 1, 1.1 + String = 35, // i.e. "text" + + Eof = 50 + } + + internal /* readonly */ struct JsonToken + { + internal static readonly JsonToken BraceOpen = new JsonToken(TokenKind.LeftBrace, "{"); + internal static readonly JsonToken BraceClose = new JsonToken(TokenKind.RightBrace, "}"); + + internal static readonly JsonToken BracketOpen = new JsonToken(TokenKind.LeftBracket, "["); + internal static readonly JsonToken BracketClose = new JsonToken(TokenKind.RightBracket, "]"); + + internal static readonly JsonToken Colon = new JsonToken(TokenKind.Colon, ":"); + internal static readonly JsonToken Comma = new JsonToken(TokenKind.Comma, ","); + internal static readonly JsonToken Terminator = new JsonToken(TokenKind.Terminator, "\0"); + + internal static readonly JsonToken True = new JsonToken(TokenKind.Boolean, "true"); + internal static readonly JsonToken False = new JsonToken(TokenKind.Boolean, "false"); + internal static readonly JsonToken Null = new JsonToken(TokenKind.Null, "null"); + + internal static readonly JsonToken Eof = new JsonToken(TokenKind.Eof, null); + + internal JsonToken(TokenKind kind, string value) + { + Kind = kind; + Value = value; + } + + internal readonly TokenKind Kind; + + internal readonly string Value; + + public override string ToString() => Kind + ": " + Value; + + #region Helpers + + internal bool IsLiteral => (byte)Kind > 30 && (byte)Kind < 40; + + internal bool IsTerminator => Kind == TokenKind.Terminator; + + #endregion + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Parser/JsonTokenizer.cs b/src/AppConfiguration/generated/runtime/Parser/JsonTokenizer.cs new file mode 100644 index 000000000000..10bdd15edd1c --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Parser/JsonTokenizer.cs @@ -0,0 +1,177 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Text; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + using System.IO; + + + public class JsonTokenizer : IDisposable + { + private readonly StringBuilder sb = new StringBuilder(); + + private readonly SourceReader reader; + + internal JsonTokenizer(TextReader reader) + : this(new SourceReader(reader)) { } + + internal JsonTokenizer(SourceReader reader) + { + this.reader = reader; + + reader.Next(); // Start with the first char + } + + internal JsonToken ReadNext() + { + reader.SkipWhitespace(); + + if (reader.IsEof) return JsonToken.Eof; + + switch (reader.Current) + { + case '"': return ReadQuotedString(); + + // Symbols + case '[' : reader.Next(); return JsonToken.BracketOpen; // Array start + case ']' : reader.Next(); return JsonToken.BracketClose; // Array end + case ',' : reader.Next(); return JsonToken.Comma; // Value seperator + case ':' : reader.Next(); return JsonToken.Colon; // Field value indicator + case '{' : reader.Next(); return JsonToken.BraceOpen; // Object start + case '}' : reader.Next(); return JsonToken.BraceClose; // Object end + case '\0' : reader.Next(); return JsonToken.Terminator; // Stream terminiator + + default: return ReadLiteral(); + } + } + + private JsonToken ReadQuotedString() + { + Expect('"', "quoted string indicator"); + + reader.Next(); // Read '"' (Starting quote) + + // Read until we reach an unescaped quote char + while (reader.Current != '"') + { + EnsureNotEof("quoted string"); + + if (reader.Current == '\\') + { + char escapedCharacter = reader.ReadEscapeCode(); + + sb.Append(escapedCharacter); + + continue; + } + + StoreCurrentCharacterAndReadNext(); + } + + reader.Next(); // Read '"' (Ending quote) + + return new JsonToken(TokenKind.String, value: sb.Extract()); + } + + private JsonToken ReadLiteral() + { + if (char.IsDigit(reader.Current) || + reader.Current == '-' || + reader.Current == '+') + { + return ReadNumber(); + } + + return ReadIdentifer(); + } + + private JsonToken ReadNumber() + { + // Read until we hit a non-numeric character + // -6.247737e-06 + // E + + while (char.IsDigit(reader.Current) + || reader.Current == '.' + || reader.Current == 'e' + || reader.Current == 'E' + || reader.Current == '-' + || reader.Current == '+') + { + StoreCurrentCharacterAndReadNext(); + } + + return new JsonToken(TokenKind.Number, value: sb.Extract()); + } + + int count = 0; + + private JsonToken ReadIdentifer() + { + count++; + + if (!char.IsLetter(reader.Current)) + { + throw new ParserException( + message : $"Expected literal (number, boolean, or null). Was '{reader.Current}'.", + location : reader.Location + ); + } + + // Read letters, numbers, and underscores '_' + while (char.IsLetterOrDigit(reader.Current) || reader.Current == '_') + { + StoreCurrentCharacterAndReadNext(); + } + + string text = sb.Extract(); + + switch (text) + { + case "true": return JsonToken.True; + case "false": return JsonToken.False; + case "null": return JsonToken.Null; + + default: return new JsonToken(TokenKind.String, text); + } + } + + private void Expect(char character, string description) + { + if (reader.Current != character) + { + throw new ParserException( + message: $"Expected {description} ('{character}'). Was '{reader.Current}'.", + location: reader.Location + ); + } + } + + private void EnsureNotEof(string tokenType) + { + if (reader.IsEof) + { + throw new ParserException( + message: $"Unexpected EOF while reading {tokenType}.", + location: reader.Location + ); + } + } + + private void StoreCurrentCharacterAndReadNext() + { + sb.Append(reader.Current); + + reader.Next(); + } + + public void Dispose() + { + reader.Dispose(); + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Parser/Location.cs b/src/AppConfiguration/generated/runtime/Parser/Location.cs new file mode 100644 index 000000000000..f741fc6e305f --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Parser/Location.cs @@ -0,0 +1,43 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal struct SourceLocation + { + private int line; + private int column; + private int position; + + internal SourceLocation(int line = 0, int column = 0, int position = 0) + { + this.line = line; + this.column = column; + this.position = position; + } + + internal int Line => line; + + internal int Column => column; + + internal int Position => position; + + internal void Advance() + { + this.column++; + this.position++; + } + + internal void MarkNewLine() + { + this.line++; + this.column = 0; + } + + internal SourceLocation Clone() + { + return new SourceLocation(line, column, position); + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Parser/Readers/SourceReader.cs b/src/AppConfiguration/generated/runtime/Parser/Readers/SourceReader.cs new file mode 100644 index 000000000000..d5e820390268 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Parser/Readers/SourceReader.cs @@ -0,0 +1,130 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Globalization; +using System.IO; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public sealed class SourceReader : IDisposable + { + private readonly TextReader source; + + private char current; + + private readonly SourceLocation location = new SourceLocation(); + + private bool isEof = false; + + internal SourceReader(TextReader textReader) + { + this.source = textReader ?? throw new ArgumentNullException(nameof(textReader)); + } + + /// + /// Advances to the next character + /// + internal void Next() + { + // Advance to the new line when we see a new line '\n'. + // A new line may be prefixed by a carriage return '\r'. + + if (current == '\n') + { + location.MarkNewLine(); + } + + int charCode = source.Read(); // -1 for end + + if (charCode >= 0) + { + current = (char)charCode; + } + else + { + // If we've already marked this as the EOF, throw an exception + if (isEof) + { + throw new EndOfStreamException("Cannot advance past end of stream."); + } + + isEof = true; + + current = '\0'; + } + + location.Advance(); + } + + internal void SkipWhitespace() + { + while (char.IsWhiteSpace(current)) + { + Next(); + } + } + + internal char ReadEscapeCode() + { + Next(); + + char escapedChar = current; + + Next(); // Consume escaped character + + switch (escapedChar) + { + // Special escape codes + case '"': return '"'; // " (Quotation mark) U+0022 + case '/': return '/'; // / (Solidus) U+002F + case '\\': return '\\'; // \ (Reverse solidus) U+005C + + // Control Characters + case '0': return '\0'; // Nul (0) U+0000 + case 'a': return '\a'; // Alert (7) + case 'b': return '\b'; // Backspace (8) U+0008 + case 'f': return '\f'; // Form feed (12) U+000C + case 'n': return '\n'; // Line feed (10) U+000A + case 'r': return '\r'; // Carriage return (13) U+000D + case 't': return '\t'; // Horizontal tab (9) U+0009 + case 'v': return '\v'; // Vertical tab + + // Unicode escape sequence + case 'u': return ReadUnicodeEscapeSequence(); // U+XXXX + + default: throw new Exception($"Unrecognized escape sequence '\\{escapedChar}'"); + } + } + + private readonly char[] hexCode = new char[4]; + + private char ReadUnicodeEscapeSequence() + { + hexCode[0] = current; Next(); + hexCode[1] = current; Next(); + hexCode[2] = current; Next(); + hexCode[3] = current; Next(); + + return Convert.ToChar(int.Parse( + s : new string(hexCode), + style : NumberStyles.HexNumber, + provider: NumberFormatInfo.InvariantInfo + )); + } + + internal char Current => current; + + internal bool IsEof => isEof; + + internal char Peek() => (char)source.Peek(); + + internal SourceLocation Location => location; + + public void Dispose() + { + source.Dispose(); + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Parser/TokenReader.cs b/src/AppConfiguration/generated/runtime/Parser/TokenReader.cs new file mode 100644 index 000000000000..c1b53e058f22 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Parser/TokenReader.cs @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + public class TokenReader : IDisposable + { + private readonly JsonTokenizer tokenizer; + private JsonToken current; + + internal TokenReader(JsonTokenizer tokenizer) + { + this.tokenizer = tokenizer ?? throw new ArgumentNullException(nameof(tokenizer)); + } + + internal void Next() + { + current = tokenizer.ReadNext(); + } + + internal JsonToken Current => current; + + internal void Ensure(TokenKind kind, string readerName) + { + if (current.Kind != kind) + { + throw new ParserException($"Expected {kind} while reading {readerName}). Was {current}."); + } + } + + public void Dispose() + { + tokenizer.Dispose(); + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/PipelineMocking.cs b/src/AppConfiguration/generated/runtime/PipelineMocking.cs new file mode 100644 index 000000000000..fc458a087ca3 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/PipelineMocking.cs @@ -0,0 +1,254 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + using System.Threading.Tasks; + using System.Collections.Generic; + using System.Net.Http; + using System.Linq; + using System.Net; + using Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json; + + public enum MockMode + { + Live, + Record, + Playback, + + } + + public class PipelineMock + { + + private System.Collections.Generic.Stack scenario = new System.Collections.Generic.Stack(); + private System.Collections.Generic.Stack context = new System.Collections.Generic.Stack(); + private System.Collections.Generic.Stack description = new System.Collections.Generic.Stack(); + + private readonly string recordingPath; + private int counter = 0; + + public static implicit operator Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep(PipelineMock instance) => instance.SendAsync; + + public MockMode Mode { get; set; } = MockMode.Live; + public PipelineMock(string recordingPath) + { + this.recordingPath = recordingPath; + } + + public void PushContext(string text) => context.Push(text); + + public void PushDescription(string text) => description.Push(text); + + + public void PushScenario(string it) + { + // reset counter too + counter = 0; + + scenario.Push(it); + } + + public void PopContext() => context.Pop(); + + public void PopDescription() => description.Pop(); + + public void PopScenario() => scenario.Pop(); + + public void SetRecord() => Mode = MockMode.Record; + + public void SetPlayback() => Mode = MockMode.Playback; + + public void SetLive() => Mode = MockMode.Live; + + public string Scenario => (scenario.Count > 0 ? scenario.Peek() : "[NoScenario]"); + public string Description => (description.Count > 0 ? description.Peek() : "[NoDescription]"); + public string Context => (context.Count > 0 ? context.Peek() : "[NoContext]"); + + /// + /// Headers that we substitute out blank values for in the recordings + /// Add additional headers as necessary + /// + public static HashSet Blacklist = new HashSet(System.StringComparer.CurrentCultureIgnoreCase) { + "Authorization", + }; + + public Dictionary ForceResponseHeaders = new Dictionary(); + + internal static XImmutableArray Removed = new XImmutableArray(new string[] { "[Filtered]" }); + + internal static IEnumerable> FilterHeaders(IEnumerable>> headers) => headers.Select(header => new KeyValuePair(header.Key, Blacklist.Contains(header.Key) ? Removed : new XImmutableArray(header.Value.ToArray()))); + + internal static JsonNode SerializeContent(HttpContent content) => content == null ? XNull.Instance : SerializeContent(content.ReadAsByteArrayAsync().Result); + + internal static JsonNode SerializeContent(byte[] content) + { + if (null == content || content.Length == 0) + { + return XNull.Instance; + } + var first = content[0]; + var last = content[content.Length - 1]; + + // plaintext for JSON/SGML/XML/HTML/STRINGS/ARRAYS + if ((first == '{' && last == '}') || (first == '<' && last == '>') || (first == '[' && last == ']') || (first == '"' && last == '"')) + { + return new JsonString(System.Text.Encoding.UTF8.GetString(content)); + } + + // base64 for everyone else + return new JsonString(System.Convert.ToBase64String(content)); + } + + internal static byte[] DeserializeContent(string content) + { + if (string.IsNullOrWhiteSpace(content)) + { + return new byte[0]; + } + + if (content.EndsWith("==")) + { + try + { + return System.Convert.FromBase64String(content); + } + catch + { + // hmm. didn't work, return it as a string I guess. + } + } + return System.Text.Encoding.UTF8.GetBytes(content); + } + + public void SaveMessage(string rqKey, HttpRequestMessage request, HttpResponseMessage response) + { + var messages = System.IO.File.Exists(this.recordingPath) ? Load() : new JsonObject() ?? new JsonObject(); + messages[rqKey] = new JsonObject { + { "Request",new JsonObject { + { "Method", request.Method.Method }, + { "RequestUri", request.RequestUri }, + { "Content", SerializeContent( request.Content) }, + { "Headers", new JsonObject(FilterHeaders(request.Headers)) }, + { "ContentHeaders", request.Content == null ? new JsonObject() : new JsonObject(FilterHeaders(request.Content.Headers))} + } }, + {"Response", new JsonObject { + { "StatusCode", (int)response.StatusCode}, + { "Headers", new JsonObject(FilterHeaders(response.Headers))}, + { "ContentHeaders", new JsonObject(FilterHeaders(response.Content.Headers))}, + { "Content", SerializeContent(response.Content) }, + }} + }; + System.IO.File.WriteAllText(this.recordingPath, messages.ToString()); + } + + private JsonObject Load() + { + if (System.IO.File.Exists(this.recordingPath)) + { + try + { + return JsonObject.FromStream(System.IO.File.OpenRead(this.recordingPath)); + } + catch + { + throw new System.Exception($"Invalid recording file: '{recordingPath}'"); + } + } + + throw new System.ArgumentException($"Missing recording file: '{recordingPath}'", nameof(recordingPath)); + } + + public HttpResponseMessage LoadMessage(string rqKey) + { + var responses = Load(); + var message = responses.Property(rqKey); + + if (null == message) + { + throw new System.ArgumentException($"Missing Request '{rqKey}' in recording file", nameof(rqKey)); + } + + var sc = 0; + var reqMessage = message.Property("Request"); + var respMessage = message.Property("Response"); + + // --------------------------- deserialize response ---------------------------------------------------------------- + var response = new HttpResponseMessage + { + StatusCode = (HttpStatusCode)respMessage.NumberProperty("StatusCode", ref sc), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(respMessage.StringProperty("Content"))) + }; + + foreach (var each in respMessage.Property("Headers")) + { + response.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + foreach (var frh in ForceResponseHeaders) + { + response.Headers.Remove(frh.Key); + response.Headers.TryAddWithoutValidation(frh.Key, frh.Value); + } + + foreach (var each in respMessage.Property("ContentHeaders")) + { + response.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + // --------------------------- deserialize request ---------------------------------------------------------------- + response.RequestMessage = new HttpRequestMessage + { + Method = new HttpMethod(reqMessage.StringProperty("Method")), + RequestUri = new System.Uri(reqMessage.StringProperty("RequestUri")), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(reqMessage.StringProperty("Content"))) + }; + + foreach (var each in reqMessage.Property("Headers")) + { + response.RequestMessage.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + foreach (var each in reqMessage.Property("ContentHeaders")) + { + response.RequestMessage.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + return response; + } + + public async Task SendAsync(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + counter++; + var rqkey = $"{Description}+{Context}+{Scenario}+${request.Method.Method}+{request.RequestUri}+{counter}"; + + switch (Mode) + { + case MockMode.Record: + //Add following code since the request.Content will be released after sendAsync + var requestClone = request; + if (requestClone.Content != null) + { + requestClone = await request.CloneWithContent(request.RequestUri, request.Method); + } + // make the call + var response = await next.SendAsync(request, callback); + + // save the message to the recording file + SaveMessage(rqkey, requestClone, response); + + // return the response. + return response; + + case MockMode.Playback: + // load and return the response. + return LoadMessage(rqkey); + + default: + // pass-thru, do nothing + return await next.SendAsync(request, callback); + } + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Response.cs b/src/AppConfiguration/generated/runtime/Response.cs new file mode 100644 index 000000000000..c49937dd5ccd --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Response.cs @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + using System; + using System.Threading.Tasks; + public class Response : EventData + { + public Response() : base() + { + } + } + + public class Response : Response + { + private Func> _resultDelegate; + private Task _resultValue; + + public Response(T value) : base() => _resultValue = Task.FromResult(value); + public Response(Func value) : base() => _resultDelegate = () => Task.FromResult(value()); + public Response(Func> value) : base() => _resultDelegate = value; + public Task Result => _resultValue ?? (_resultValue = this._resultDelegate()); + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Serialization/JsonSerializer.cs b/src/AppConfiguration/generated/runtime/Serialization/JsonSerializer.cs new file mode 100644 index 000000000000..f3cb08fecaf1 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Serialization/JsonSerializer.cs @@ -0,0 +1,350 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal class JsonSerializer + { + private int depth = 0; + + private SerializationOptions options = new SerializationOptions(); + + #region Deserialization + + internal T Deseralize(JsonObject json) + where T : new() + { + var contract = JsonModelCache.Get(typeof(T)); + + return (T)DeserializeObject(contract, json); + } + + internal object DeserializeObject(JsonModel contract, JsonObject json) + { + var instance = Activator.CreateInstance(contract.Type); + + depth++; + + // Ensure we don't recurse forever + if (depth > 5) throw new Exception("Depth greater than 5"); + + foreach (var field in json) + { + var member = contract[field.Key]; + + if (member != null) + { + var value = DeserializeValue(member, field.Value); + + member.SetValue(instance, value); + } + } + + depth--; + + return instance; + } + + private object DeserializeValue(JsonMember member, JsonNode value) + { + if (value.Type == JsonType.Null) return null; + + var type = member.Type; + + if (member.IsStringLike && value.Type != JsonType.String) + { + // Take the long path... + return DeserializeObject(JsonModelCache.Get(type), (JsonObject)value); + } + else if (member.Converter != null) + { + return member.Converter.FromJson(value); + } + else if (type.IsArray) + { + return DeserializeArray(type, (JsonArray)value); + } + else if (member.IsList) + { + return DeserializeList(type, (JsonArray)value); + } + else + { + var contract = JsonModelCache.Get(type); + + return DeserializeObject(contract, (JsonObject)value); + } + } + + private object DeserializeValue(Type type, JsonNode value) + { + if (type == null) throw new ArgumentNullException(nameof(type)); + + if (value.Type == JsonType.Null) return null; + + var typeDetails = TypeDetails.Get(type); + + if (typeDetails.JsonConverter != null) + { + return typeDetails.JsonConverter.FromJson(value); + } + else if (typeDetails.IsEnum) + { + return Enum.Parse(type, value.ToString(), ignoreCase: true); + } + else if (type.IsArray) + { + return DeserializeArray(type, (JsonArray)value); + } + else if (typeDetails.IsList) + { + return DeserializeList(type, (JsonArray)value); + } + else + { + var contract = JsonModelCache.Get(type); + + return DeserializeObject(contract, (JsonObject)value); + } + } + + internal Array DeserializeArray(Type type, JsonArray elements) + { + var elementType = type.GetElementType(); + + var elementTypeDetails = TypeDetails.Get(elementType); + + var array = Array.CreateInstance(elementType, elements.Count); + + int i = 0; + + if (elementTypeDetails.JsonConverter != null) + { + foreach (var value in elements) + { + array.SetValue(elementTypeDetails.JsonConverter.FromJson(value), i); + + i++; + } + } + else + { + foreach (var value in elements) + { + array.SetValue(DeserializeValue(elementType, value), i); + + i++; + } + } + + return array; + } + + internal IList DeserializeList(Type type, JsonArray jsonArray) + { + // TODO: Handle non-generic types + if (!type.IsGenericType) + throw new ArgumentException("Must be a generic type", nameof(type)); + + var elementType = type.GetGenericArguments()[0]; + + IList list; + + if (type.IsInterface) + { + // Create a concrete generic list + list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(elementType)); + } + else + { + list = (IList)Activator.CreateInstance(type); + } + + foreach (var value in jsonArray) + { + list.Add(DeserializeValue(elementType, value)); + } + + return list; + } + + #endregion + + #region Serialization + + internal JsonNode Serialize(object instance) => + Serialize(instance, SerializationOptions.Default); + + internal JsonNode Serialize(object instance, string[] include) => + Serialize(instance, new SerializationOptions { Include = include }); + + internal JsonNode Serialize(object instance, SerializationOptions options) + { + this.options = options; + + if (instance == null) + { + return XNull.Instance; + } + + return ReadValue(instance.GetType(), instance); + } + + #region Readers + + internal JsonArray ReadArray(IEnumerable collection) + { + var array = new XNodeArray(); + + foreach (var item in collection) + { + array.Add(ReadValue(item.GetType(), item)); + } + + return array; + } + + internal IEnumerable> ReadProperties(object instance) + { + var contract = JsonModelCache.Get(instance.GetType()); + + foreach (var member in contract.Members) + { + string name = member.Name; + + if (options.PropertyNameTransformer != null) + { + name = options.PropertyNameTransformer.Invoke(name); + } + + // Skip the field if it's not included + if ((depth == 1 && !options.IsIncluded(name))) + { + continue; + } + + var value = member.GetValue(instance); + + if (!member.EmitDefaultValue && (value == null || (member.IsList && ((IList)value).Count == 0) || value.Equals(member.DefaultValue))) + { + continue; + } + else if (options.IgnoreNullValues && value == null) // Ignore null values + { + continue; + } + + // Transform the value if there is one + if (options.Transformations != null) + { + var transform = options.GetTransformation(name); + + if (transform != null) + { + value = transform.Transformer(value); + } + } + + yield return new KeyValuePair(name, ReadValue(member.TypeDetails, value)); + } + } + + private JsonObject ReadObject(object instance) + { + depth++; + + // TODO: Guard against a self referencing graph + if (depth > options.MaxDepth) + { + depth--; + + return new JsonObject(); + } + + var node = new JsonObject(ReadProperties(instance)); + + depth--; + + return node; + } + + private JsonNode ReadValue(Type type, object value) + { + if (value == null) + { + return XNull.Instance; + } + + var member = TypeDetails.Get(type); + + return ReadValue(member, value); + } + + private JsonNode ReadValue(TypeDetails type, object value) + { + if (value == null) + { + return XNull.Instance; + } + + if (type.JsonConverter != null) + { + return type.JsonConverter.ToJson(value); + } + else if (type.IsArray) + { + switch (Type.GetTypeCode(type.ElementType)) + { + case TypeCode.String: return CreateArray((string[])value); + case TypeCode.UInt16: return CreateArray((ushort[])value); + case TypeCode.UInt32: return CreateArray((uint[])value); + case TypeCode.UInt64: return CreateArray((ulong[])value); + case TypeCode.Int16: return CreateArray((short[])value); + case TypeCode.Int32: return CreateArray((int[])value); + case TypeCode.Int64: return CreateArray((long[])value); + case TypeCode.Single: return CreateArray((float[])value); + case TypeCode.Double: return CreateArray((double[])value); + default: return ReadArray((IEnumerable)value); + } + } + else if (value is IEnumerable) + { + if (type.IsList && type.ElementType != null) + { + switch (Type.GetTypeCode(type.ElementType)) + { + case TypeCode.String: return CreateList(value); + case TypeCode.UInt16: return CreateList(value); + case TypeCode.UInt32: return CreateList(value); + case TypeCode.UInt64: return CreateList(value); + case TypeCode.Int16: return CreateList(value); + case TypeCode.Int32: return CreateList(value); + case TypeCode.Int64: return CreateList(value); + case TypeCode.Single: return CreateList(value); + case TypeCode.Double: return CreateList(value); + } + } + + return ReadArray((IEnumerable)value); + } + else + { + // Complex object + return ReadObject(value); + } + } + + private XList CreateList(object value) => new XList((IList)value); + + private XImmutableArray CreateArray(T[] array) => new XImmutableArray(array); + + #endregion + + #endregion + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Serialization/PropertyTransformation.cs b/src/AppConfiguration/generated/runtime/Serialization/PropertyTransformation.cs new file mode 100644 index 000000000000..24339b84b7b0 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Serialization/PropertyTransformation.cs @@ -0,0 +1,21 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal class PropertyTransformation + { + internal PropertyTransformation(string name, Func transformer) + { + Name = name ?? throw new ArgumentNullException(nameof(name)); + Transformer = transformer ?? throw new ArgumentNullException(nameof(transformer)); + } + + internal string Name { get; } + + internal Func Transformer { get; } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Serialization/SerializationOptions.cs b/src/AppConfiguration/generated/runtime/Serialization/SerializationOptions.cs new file mode 100644 index 000000000000..1baad0d3a442 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Serialization/SerializationOptions.cs @@ -0,0 +1,65 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal class SerializationOptions + { + internal static readonly SerializationOptions Default = new SerializationOptions(); + + internal SerializationOptions() { } + + internal SerializationOptions( + string[] include = null, + bool ingoreNullValues = false) + { + Include = include; + IgnoreNullValues = ingoreNullValues; + } + + internal string[] Include { get; set; } + + internal string[] Exclude { get; set; } + + internal bool IgnoreNullValues { get; set; } + + internal PropertyTransformation[] Transformations { get; set; } + + internal Func PropertyNameTransformer { get; set; } + + internal int MaxDepth { get; set; } = 5; + + internal bool IsIncluded(string name) + { + if (Exclude != null) + { + return !Exclude.Any(exclude => exclude.Equals(name, StringComparison.OrdinalIgnoreCase)); + } + else if (Include != null) + { + return Include.Any(exclude => exclude.Equals(name, StringComparison.OrdinalIgnoreCase)); + } + + return true; + } + + internal PropertyTransformation GetTransformation(string propertyName) + { + if (Transformations == null) return null; + + foreach (var t in Transformations) + { + if (t.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase)) + { + return t; + } + } + + return null; + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/SerializationMode.cs b/src/AppConfiguration/generated/runtime/SerializationMode.cs new file mode 100644 index 000000000000..6506a9276cf1 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/SerializationMode.cs @@ -0,0 +1,16 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + [System.Flags] + public enum SerializationMode + { + None = 0, + IncludeHeaders = 1 << 0, + IncludeReadOnly = 1 << 1, + + IncludeAll = IncludeHeaders | IncludeReadOnly + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/TypeConverterExtensions.cs b/src/AppConfiguration/generated/runtime/TypeConverterExtensions.cs new file mode 100644 index 000000000000..6b96ef75365a --- /dev/null +++ b/src/AppConfiguration/generated/runtime/TypeConverterExtensions.cs @@ -0,0 +1,190 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Serialization; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.PowerShell +{ + internal static class TypeConverterExtensions + { + internal static T[] SelectToArray(object source, System.Func converter) + { + // null begets null + if (source == null) + { + return null; + } + + // single values and strings are just encapsulated in the array. + if (source is string || !(source is System.Collections.IEnumerable)) + { + try + { + return new T[] { (T)converter(source) }; + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + return new T[0]; // empty result if couldn't convert. + } + + var result = new System.Collections.Generic.List(); + foreach (var each in (System.Collections.IEnumerable)source) + { + try + { + result.Add((T)converter(each)); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + } + return result.ToArray(); + } + + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.Generic.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Management.Automation.PSObject instance) + { + if (null != instance) + { + foreach (var each in instance.Properties) + { + yield return each; + } + } + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.Generic.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys.OfType() + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Management.Automation.PSObject instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + // new global::System.Collections.Generic.HashSet(System.StringComparer.InvariantCultureIgnoreCase) + return (null == instance || !instance.Properties.Any()) ? + Enumerable.Empty>() : + instance.Properties + .Where(property => + !(true == exclusions?.Contains(property.Name)) + && (false != inclusions?.Contains(property.Name))) + .Select(property => new System.Collections.Generic.KeyValuePair(property.Name, property.Value)); + } + + + internal static T GetValueForProperty(this System.Collections.Generic.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys, each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + internal static T GetValueForProperty(this System.Collections.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys.OfType(), each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + + internal static T GetValueForProperty(this System.Management.Automation.PSObject psObject, string propertyName, T defaultValue, System.Func converter) + { + try + { + var property = System.Linq.Enumerable.FirstOrDefault(psObject.Properties, each => System.String.Equals(each.Name.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return property == null ? defaultValue : (T)converter(property.Value); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + } +} diff --git a/src/AppConfiguration/generated/runtime/UndeclaredResponseException.cs b/src/AppConfiguration/generated/runtime/UndeclaredResponseException.cs new file mode 100644 index 000000000000..54a257824985 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/UndeclaredResponseException.cs @@ -0,0 +1,104 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using static Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Extensions; + + public class RestException : Exception, IDisposable + { + public System.Net.HttpStatusCode StatusCode { get; set; } + public string Code { get; protected set; } + protected string message; + public HttpRequestMessage RequestMessage { get; protected set; } + public HttpResponseHeaders ResponseHeaders { get; protected set; } + + public string ResponseBody { get; protected set; } + public string ClientRequestId { get; protected set; } + public string RequestId { get; protected set; } + + public override string Message => message; + public string Action { get; protected set; } + + public RestException(System.Net.Http.HttpResponseMessage response) + { + StatusCode = response.StatusCode; + //CloneWithContent will not work here since the content is disposed after sendAsync + //Besides, it seems there is no need for the request content cloned here. + RequestMessage = response.RequestMessage.Clone(); + ResponseBody = response.Content.ReadAsStringAsync().Result; + ResponseHeaders = response.Headers; + + RequestId = response.GetFirstHeader("x-ms-request-id"); + ClientRequestId = response.GetFirstHeader("x-ms-client-request-id"); + + try + { + // try to parse the body as JSON, and see if a code and message are in there. + var json = Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json.JsonObject; + + // see if there is an error block in the body + json = json.Property("error") ?? json; + + { Code = If(json?.PropertyT("code"), out var c) ? (string)c : (string)StatusCode.ToString(); } + { message = If(json?.PropertyT("message"), out var m) ? (string)m : (string)Message; } + { Action = If(json?.PropertyT("action"), out var a) ? (string)a : (string)Action; } + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // couldn't get the code/message from the body response. + // we'll create one below. + } +#endif + if (string.IsNullOrEmpty(message)) + { + if (StatusCode >= System.Net.HttpStatusCode.BadRequest && StatusCode < System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Request Error, Status: {StatusCode}"; + } + else if (StatusCode >= System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Server Error, Status: {StatusCode}"; + } + else + { + message = $"The server responded with an unrecognized response, Status: {StatusCode}"; + } + } + } + + public void Dispose() + { + ((IDisposable)RequestMessage).Dispose(); + } + } + + public class RestException : RestException + { + public T Error { get; protected set; } + public RestException(System.Net.Http.HttpResponseMessage response, T error) : base(response) + { + Error = error; + } + } + + + public class UndeclaredResponseException : RestException + { + public UndeclaredResponseException(System.Net.Http.HttpResponseMessage response) : base(response) + { + + } + } +} \ No newline at end of file diff --git a/src/AppConfiguration/generated/runtime/Writers/JsonWriter.cs b/src/AppConfiguration/generated/runtime/Writers/JsonWriter.cs new file mode 100644 index 000000000000..b7dd1365fefa --- /dev/null +++ b/src/AppConfiguration/generated/runtime/Writers/JsonWriter.cs @@ -0,0 +1,223 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Web; + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Json +{ + internal class JsonWriter + { + const string indentation = " "; // 2 spaces + + private readonly bool pretty; + private readonly TextWriter writer; + + protected int currentLevel = 0; + + internal JsonWriter(TextWriter writer, bool pretty = true) + { + this.writer = writer ?? throw new ArgumentNullException(nameof(writer)); + this.pretty = pretty; + } + + internal void WriteNode(JsonNode node) + { + switch (node.Type) + { + case JsonType.Array: WriteArray((IEnumerable)node); break; + case JsonType.Object: WriteObject((JsonObject)node); break; + + // Primitives + case JsonType.Binary: WriteBinary((XBinary)node); break; + case JsonType.Boolean: WriteBoolean((bool)node); break; + case JsonType.Date: WriteDate((JsonDate)node); break; + case JsonType.Null: WriteNull(); break; + case JsonType.Number: WriteNumber((JsonNumber)node); break; + case JsonType.String: WriteString(node); break; + } + } + + internal void WriteArray(IEnumerable array) + { + currentLevel++; + + writer.Write('['); + + bool doIndentation = false; + + if (pretty) + { + foreach (var node in array) + { + if (node.Type == JsonType.Object || node.Type == JsonType.Array) + { + doIndentation = true; + + break; + } + } + } + + bool isFirst = true; + + foreach (JsonNode node in array) + { + if (!isFirst) writer.Write(','); + + if (doIndentation) + { + WriteIndent(); + } + else if (pretty) + { + writer.Write(' '); + } + + WriteNode(node); + + isFirst = false; + } + + currentLevel--; + + if (doIndentation) + { + WriteIndent(); + } + else if (pretty) + { + writer.Write(' '); + } + + writer.Write(']'); + } + + internal void WriteIndent() + { + if (pretty) + { + writer.Write(Environment.NewLine); + + for (int level = 0; level < currentLevel; level++) + { + writer.Write(indentation); + } + } + } + + internal void WriteObject(JsonObject obj) + { + currentLevel++; + + writer.Write('{'); + + bool isFirst = true; + + foreach (var field in obj) + { + if (!isFirst) writer.Write(','); + + WriteIndent(); + + WriteFieldName(field.Key); + + writer.Write(':'); + + if (pretty) + { + writer.Write(' '); + } + + // Write the field value + WriteNode(field.Value); + + isFirst = false; + } + + currentLevel--; + + WriteIndent(); + + writer.Write('}'); + } + + internal void WriteFieldName(string fieldName) + { + writer.Write('"'); + writer.Write(HttpUtility.JavaScriptStringEncode(fieldName)); + writer.Write('"'); + } + + #region Primitives + + internal void WriteBinary(XBinary value) + { + writer.Write('"'); + writer.Write(value.ToString()); + writer.Write('"'); + } + + internal void WriteBoolean(bool value) + { + writer.Write(value ? "true" : "false"); + } + + internal void WriteDate(JsonDate date) + { + if (date.ToDateTime().Year == 1) + { + WriteNull(); + } + else + { + writer.Write('"'); + writer.Write(date.ToIsoString()); + writer.Write('"'); + } + } + + internal void WriteNull() + { + writer.Write("null"); + } + + internal void WriteNumber(JsonNumber number) + { + if (number.Overflows) + { + writer.Write('"'); + writer.Write(number.Value); + writer.Write('"'); + } + else + { + writer.Write(number.Value); + } + } + + internal void WriteString(string text) + { + if (text == null) + { + WriteNull(); + } + else + { + writer.Write('"'); + + writer.Write(HttpUtility.JavaScriptStringEncode(text)); + + writer.Write('"'); + } + } + + #endregion + } +} + + +// TODO: Replace with System.Text.Json when available diff --git a/src/AppConfiguration/generated/runtime/delegates.cs b/src/AppConfiguration/generated/runtime/delegates.cs new file mode 100644 index 000000000000..4c5aa57a1bb3 --- /dev/null +++ b/src/AppConfiguration/generated/runtime/delegates.cs @@ -0,0 +1,23 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using GetEventData=System.Func; + + public delegate Task SendAsync(HttpRequestMessage request, IEventListener callback); + public delegate Task SendAsyncStep(HttpRequestMessage request, IEventListener callback, ISendAsync next); + public delegate Task SignalEvent(string id, CancellationToken token, GetEventData getEventData); + public delegate Task Event(EventData message); + public delegate void SynchEvent(EventData message); + public delegate Task OnResponse(Response message); + public delegate Task OnResponse(Response message); +} \ No newline at end of file diff --git a/src/AppConfiguration/help/Az.AppConfiguration.md b/src/AppConfiguration/help/Az.AppConfiguration.md new file mode 100644 index 000000000000..c0dc5492c503 --- /dev/null +++ b/src/AppConfiguration/help/Az.AppConfiguration.md @@ -0,0 +1,34 @@ +--- +Module Name: Az.AppConfiguration +Module Guid: 3ff16738-381e-4d5a-9d90-c7ef6816f78e +Download Help Link: https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration +Help Version: 1.0.0.0 +Locale: en-US +--- + +# Az.AppConfiguration Module +## Description +Microsoft Azure PowerShell: AppConfiguration cmdlets + +## Az.AppConfiguration Cmdlets +### [Get-AzAppConfigurationStore](Get-AzAppConfigurationStore.md) +Gets the properties of the specified configuration store. + +### [Get-AzAppConfigurationStoreKey](Get-AzAppConfigurationStoreKey.md) +Lists the access key for the specified configuration store. + +### [New-AzAppConfigurationStore](New-AzAppConfigurationStore.md) +Creates a configuration store with the specified parameters. + +### [New-AzAppConfigurationStoreKey](New-AzAppConfigurationStoreKey.md) +Regenerates an access key for the specified configuration store. + +### [Remove-AzAppConfigurationStore](Remove-AzAppConfigurationStore.md) +Deletes a configuration store. + +### [Test-AzAppConfigurationStoreNameAvailability](Test-AzAppConfigurationStoreNameAvailability.md) +Checks whether the configuration store name is available for use. + +### [Update-AzAppConfigurationStore](Update-AzAppConfigurationStore.md) +Updates a configuration store with the specified parameters. + diff --git a/src/AppConfiguration/help/Get-AzAppConfigurationStore.md b/src/AppConfiguration/help/Get-AzAppConfigurationStore.md new file mode 100644 index 000000000000..2708cd6c530a --- /dev/null +++ b/src/AppConfiguration/help/Get-AzAppConfigurationStore.md @@ -0,0 +1,163 @@ +--- +external help file: +Module Name: Az.AppConfiguration +online version: https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/get-azappconfigurationstore +schema: 2.0.0 +--- + +# Get-AzAppConfigurationStore + +## SYNOPSIS +Gets the properties of the specified configuration store. + +## SYNTAX + +### List (Default) +``` +Get-AzAppConfigurationStore [-SubscriptionId ] [-SkipToken ] [-DefaultProfile ] + [] +``` + +### Get +``` +Get-AzAppConfigurationStore -Name -ResourceGroupName [-SubscriptionId ] + [-DefaultProfile ] [] +``` + +### GetViaIdentity +``` +Get-AzAppConfigurationStore -InputObject [-DefaultProfile ] + [] +``` + +### List1 +``` +Get-AzAppConfigurationStore -ResourceGroupName [-SubscriptionId ] [-SkipToken ] + [-DefaultProfile ] [] +``` + +## DESCRIPTION +Gets the properties of the specified configuration store. + +## PARAMETERS + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +Parameter Sets: GetViaIdentity +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +The name of the configuration store. + +```yaml +Type: System.String +Parameter Sets: Get +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group to which the container registry belongs. + +```yaml +Type: System.String +Parameter Sets: Get, List1 +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SkipToken +A skip token is used to continue retrieving items after an operation returns a partial result. +If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. + +```yaml +Type: System.String +Parameter Sets: List, List1 +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The Microsoft Azure subscription ID. + +```yaml +Type: System.String[] +Parameter Sets: Get, List, List1 +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[ConfigStoreName ]`: The name of the configuration store. + - `[Id ]`: Resource identity path + - `[ResourceGroupName ]`: The name of the resource group to which the container registry belongs. + - `[SubscriptionId ]`: The Microsoft Azure subscription ID. + +## RELATED LINKS + diff --git a/src/AppConfiguration/help/Get-AzAppConfigurationStoreKey.md b/src/AppConfiguration/help/Get-AzAppConfigurationStoreKey.md new file mode 100644 index 000000000000..861d41fe9a4a --- /dev/null +++ b/src/AppConfiguration/help/Get-AzAppConfigurationStoreKey.md @@ -0,0 +1,147 @@ +--- +external help file: +Module Name: Az.AppConfiguration +online version: https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/get-azappconfigurationstorekey +schema: 2.0.0 +--- + +# Get-AzAppConfigurationStoreKey + +## SYNOPSIS +Lists the access key for the specified configuration store. + +## SYNTAX + +``` +Get-AzAppConfigurationStoreKey -Name -ResourceGroupName [-SubscriptionId ] + [-SkipToken ] [-DefaultProfile ] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Lists the access key for the specified configuration store. + + +## PARAMETERS + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Name +The name of the configuration store. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group to which the container registry belongs. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SkipToken +A skip token is used to continue retrieving items after an operation returns a partial result. +If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The Microsoft Azure subscription ID. + +```yaml +Type: System.String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey + +## NOTES + +ALIASES + +## RELATED LINKS + diff --git a/src/AppConfiguration/help/New-AzAppConfigurationStore.md b/src/AppConfiguration/help/New-AzAppConfigurationStore.md new file mode 100644 index 000000000000..faa30d0241fa --- /dev/null +++ b/src/AppConfiguration/help/New-AzAppConfigurationStore.md @@ -0,0 +1,229 @@ +--- +external help file: +Module Name: Az.AppConfiguration +online version: https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/new-azappconfigurationstore +schema: 2.0.0 +--- + +# New-AzAppConfigurationStore + +## SYNOPSIS +Creates a configuration store with the specified parameters. + +## SYNTAX + +### CreateExpanded (Default) +``` +New-AzAppConfigurationStore -Name -ResourceGroupName -Location + [-SubscriptionId ] [-Tag ] [-DefaultProfile ] [-AsJob] [-NoWait] [-Confirm] + [-WhatIf] [] +``` + +### CreateViaIdentityExpanded +``` +New-AzAppConfigurationStore -InputObject -Location [-Tag ] + [-DefaultProfile ] [-AsJob] [-NoWait] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Creates a configuration store with the specified parameters. + + +## PARAMETERS + +### -AsJob +Run the command as a job + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +Parameter Sets: CreateViaIdentityExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Location +The location of the resource. +This cannot be changed after the resource is created. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Name +The name of the configuration store. + +```yaml +Type: System.String +Parameter Sets: CreateExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoWait +Run the command asynchronously + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group to which the container registry belongs. + +```yaml +Type: System.String +Parameter Sets: CreateExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The Microsoft Azure subscription ID. + +```yaml +Type: System.String +Parameter Sets: CreateExpanded +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Tag +The tags of the resource. + +```yaml +Type: System.Collections.Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[ConfigStoreName ]`: The name of the configuration store. + - `[Id ]`: Resource identity path + - `[ResourceGroupName ]`: The name of the resource group to which the container registry belongs. + - `[SubscriptionId ]`: The Microsoft Azure subscription ID. + +## RELATED LINKS + diff --git a/src/AppConfiguration/help/New-AzAppConfigurationStoreKey.md b/src/AppConfiguration/help/New-AzAppConfigurationStoreKey.md new file mode 100644 index 000000000000..8cfd7ecc2255 --- /dev/null +++ b/src/AppConfiguration/help/New-AzAppConfigurationStoreKey.md @@ -0,0 +1,182 @@ +--- +external help file: +Module Name: Az.AppConfiguration +online version: https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/new-azappconfigurationstorekey +schema: 2.0.0 +--- + +# New-AzAppConfigurationStoreKey + +## SYNOPSIS +Regenerates an access key for the specified configuration store. + +## SYNTAX + +### RegenerateExpanded (Default) +``` +New-AzAppConfigurationStoreKey -Name -ResourceGroupName [-SubscriptionId ] + [-Id ] [-DefaultProfile ] [-Confirm] [-WhatIf] [] +``` + +### RegenerateViaIdentityExpanded +``` +New-AzAppConfigurationStoreKey -InputObject [-Id ] + [-DefaultProfile ] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Regenerates an access key for the specified configuration store. + + +## PARAMETERS + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Id +The id of the key to regenerate. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +Parameter Sets: RegenerateViaIdentityExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +The name of the configuration store. + +```yaml +Type: System.String +Parameter Sets: RegenerateExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group to which the container registry belongs. + +```yaml +Type: System.String +Parameter Sets: RegenerateExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The Microsoft Azure subscription ID. + +```yaml +Type: System.String +Parameter Sets: RegenerateExpanded +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[ConfigStoreName ]`: The name of the configuration store. + - `[Id ]`: Resource identity path + - `[ResourceGroupName ]`: The name of the resource group to which the container registry belongs. + - `[SubscriptionId ]`: The Microsoft Azure subscription ID. + +## RELATED LINKS + diff --git a/src/AppConfiguration/help/Remove-AzAppConfigurationStore.md b/src/AppConfiguration/help/Remove-AzAppConfigurationStore.md new file mode 100644 index 000000000000..71a8f5c2f670 --- /dev/null +++ b/src/AppConfiguration/help/Remove-AzAppConfigurationStore.md @@ -0,0 +1,212 @@ +--- +external help file: +Module Name: Az.AppConfiguration +online version: https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/remove-azappconfigurationstore +schema: 2.0.0 +--- + +# Remove-AzAppConfigurationStore + +## SYNOPSIS +Deletes a configuration store. + +## SYNTAX + +### Delete (Default) +``` +Remove-AzAppConfigurationStore -Name -ResourceGroupName [-SubscriptionId ] + [-DefaultProfile ] [-AsJob] [-NoWait] [-PassThru] [-Confirm] [-WhatIf] [] +``` + +### DeleteViaIdentity +``` +Remove-AzAppConfigurationStore -InputObject [-DefaultProfile ] [-AsJob] + [-NoWait] [-PassThru] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Deletes a configuration store. + + +## PARAMETERS + +### -AsJob +Run the command as a job + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +Parameter Sets: DeleteViaIdentity +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +The name of the configuration store. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoWait +Run the command asynchronously + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +Returns true when the command succeeds + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group to which the container registry belongs. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The Microsoft Azure subscription ID. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity + +## OUTPUTS + +### System.Boolean + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[ConfigStoreName ]`: The name of the configuration store. + - `[Id ]`: Resource identity path + - `[ResourceGroupName ]`: The name of the resource group to which the container registry belongs. + - `[SubscriptionId ]`: The Microsoft Azure subscription ID. + +## RELATED LINKS + diff --git a/src/AppConfiguration/help/Test-AzAppConfigurationStoreNameAvailability.md b/src/AppConfiguration/help/Test-AzAppConfigurationStoreNameAvailability.md new file mode 100644 index 000000000000..947393da727a --- /dev/null +++ b/src/AppConfiguration/help/Test-AzAppConfigurationStoreNameAvailability.md @@ -0,0 +1,152 @@ +--- +external help file: +Module Name: Az.AppConfiguration +online version: https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/test-azappconfigurationstorenameavailability +schema: 2.0.0 +--- + +# Test-AzAppConfigurationStoreNameAvailability + +## SYNOPSIS +Checks whether the configuration store name is available for use. + +## SYNTAX + +### CheckExpanded (Default) +``` +Test-AzAppConfigurationStoreNameAvailability -Name [-SubscriptionId ] + [-DefaultProfile ] [-Confirm] [-WhatIf] [] +``` + +### CheckViaIdentityExpanded +``` +Test-AzAppConfigurationStoreNameAvailability -InputObject -Name + [-DefaultProfile ] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Checks whether the configuration store name is available for use. + + +## PARAMETERS + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +Parameter Sets: CheckViaIdentityExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +The name to check for availability. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The Microsoft Azure subscription ID. + +```yaml +Type: System.String +Parameter Sets: CheckExpanded +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[ConfigStoreName ]`: The name of the configuration store. + - `[Id ]`: Resource identity path + - `[ResourceGroupName ]`: The name of the resource group to which the container registry belongs. + - `[SubscriptionId ]`: The Microsoft Azure subscription ID. + +## RELATED LINKS + diff --git a/src/AppConfiguration/help/Update-AzAppConfigurationStore.md b/src/AppConfiguration/help/Update-AzAppConfigurationStore.md new file mode 100644 index 000000000000..ed5a60a89791 --- /dev/null +++ b/src/AppConfiguration/help/Update-AzAppConfigurationStore.md @@ -0,0 +1,203 @@ +--- +external help file: +Module Name: Az.AppConfiguration +online version: https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/update-azappconfigurationstore +schema: 2.0.0 +--- + +# Update-AzAppConfigurationStore + +## SYNOPSIS +Updates a configuration store with the specified parameters. + +## SYNTAX + +### UpdateExpanded (Default) +``` +Update-AzAppConfigurationStore -Name -ResourceGroupName -SubscriptionId + [-Tag ] [-DefaultProfile ] [-AsJob] [-Confirm] [-WhatIf] + [] +``` + +### UpdateViaIdentityExpanded +``` +Update-AzAppConfigurationStore -InputObject + [-Tag ] [-DefaultProfile ] [-AsJob] [-Confirm] [-WhatIf] + [] +``` + +## DESCRIPTION +Updates a configuration store with the specified parameters. + + +## PARAMETERS + +### -AsJob +Run the command as a job + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +Parameter Sets: UpdateViaIdentityExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +The name of the configuration store. + +```yaml +Type: System.String +Parameter Sets: UpdateExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group to which the container registry belongs. + +```yaml +Type: System.String +Parameter Sets: UpdateExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The Microsoft Azure subscription ID. + +```yaml +Type: System.String +Parameter Sets: UpdateExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Tag +The ARM resource tags. +To construct, see NOTES section for TAG properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[ConfigStoreName ]`: The name of the configuration store. + - `[Id ]`: Resource identity path + - `[ResourceGroupName ]`: The name of the resource group to which the container registry belongs. + - `[SubscriptionId ]`: The Microsoft Azure subscription ID. + +TAG : The ARM resource tags. + - `[(Any) ]`: This indicates any property can be added to this object. + +## RELATED LINKS + diff --git a/src/AppConfiguration/how-to.md b/src/AppConfiguration/how-to.md new file mode 100644 index 000000000000..43ec00c6d9d2 --- /dev/null +++ b/src/AppConfiguration/how-to.md @@ -0,0 +1,58 @@ +# How-To +This document describes how to develop for `Az.AppConfiguration`. + +## Building `Az.AppConfiguration` +To build, run the `build-module.ps1` at the root of the module directory. This will generate the proxy script cmdlets that are the cmdlets being exported by this module. After the build completes, the proxy script cmdlets will be output to the `exports` folder. To read more about the proxy script cmdlets, look at the [readme.md](exports/readme.md) in the `exports` folder. + +## Creating custom cmdlets +To add cmdlets that were not generated by the REST specification, use the `custom` folder. This folder allows you to add handwritten `.ps1` and `.cs` files. Currently, we support using `.ps1` scripts as new cmdlets or as additional low-level variants (via `ParameterSet`), and `.cs` files as low-level (variants) cmdlets that the exported script cmdlets call. We do not support exporting any `.cs` (dll) cmdlets directly. To read more about custom cmdlets, look at the [readme.md](custom/readme.md) in the `custom` folder. + +## Generating documentation +To generate documentation, the process is now integrated into the `build-module.ps1` script. If you don't want to run this process as part of `build-module.ps1`, you can provide the `-NoDocs` switch. If you want to run documentation generation after the build process, you may still run the `generate-help.ps1` script. Overall, the process will look at the documentation comments in the generated and custom cmdlets and types, and create `.md` files into the `docs` folder. Additionally, this pulls in any examples from the `examples` folder and adds them to the generated help markdown documents. To read more about examples, look at the [readme.md](examples/readme.md) in the `examples` folder. To read more about documentation, look at the [readme.md](docs/readme.md) in the `docs` folder. + +## Testing `Az.AppConfiguration` +To test the cmdlets, we use [Pester](https://github.com/pester/Pester). Tests scripts (`.ps1`) should be added to the `test` folder. To execute the Pester tests, run the `test-module.ps1` script. This will run all tests in `playback` mode within the `test` folder. To read more about testing cmdlets, look at the [readme.md](examples/readme.md) in the `examples` folder. + +## Packing `Az.AppConfiguration` +To pack `Az.AppConfiguration` for distribution, run the `pack-module.ps1` script. This will take the contents of multiple directories and certain root-folder files to create a `.nupkg`. The structure of the `.nupkg` is created so it can be loaded part of a [PSRepository](https://docs.microsoft.com/en-us/powershell/module/powershellget/register-psrepository). Additionally, this package is in a format for distribution to the [PSGallery](https://www.powershellgallery.com/). For signing an Azure module, please contact the [Azure PowerShell](https://github.com/Azure/azure-powershell) team. + +## Module Script Details +There are multiple scripts created for performing different actions for developing `Az.AppConfiguration`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.AppConfiguration.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.AppConfiguration.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.AppConfiguration`. + - `-Test`: After building, runs the `Pester` tests defined in the `test` folder. + - `-Docs`: After building, generates the Markdown documents for the modules into the `docs` folder. + - `-Pack`: After building, packages the module into a `.nupkg`. + - `-Code`: After building, opens a VSCode window with the module's directory and runs (see `-Run`) the module. + - `-Release`: Builds the module in `Release` configuration (as opposed to `Debug` configuration). + - `-NoDocs`: Supresses writing the documentation markdown files as part of the cmdlet exporting process. + - `-Debugger`: Used when attaching the debugger in Visual Studio to the PowerShell session, and running the build process without recompiling the DLL. This suppresses running the script as an isolated process. +- `run-module.ps1` + - Creates an isolated PowerShell session and loads `Az.AppConfiguration` into the session. + - Same as `-Run` in `build-module.ps1`. + - **Parameters**: [`Switch` parameters] + - `-Code`: Opens a VSCode window with the module's directory. + - Same as `-Code` in `build-module.ps1`. +- `generate-help.ps1` + - Generates the Markdown documents for the modules into the `docs` folder. + - Same as `-Docs` in `build-module.ps1`. +- `test-module.ps1` + - Runs the `Pester` tests defined in the `test` folder. + - Same as `-Test` in `build-module.ps1`. +- `pack-module.ps1` + - Packages the module into a `.nupkg` for distribution. + - Same as `-Pack` in `build-module.ps1`. +- `generate-help.ps1` + - Generates the Markdown documents for the modules into the `docs` folder. + - Same as `-Docs` in `build-module.ps1`. + - This process is now integrated into `build-module.ps1` automatically. To disable, use `-NoDocs` when running `build-module.ps1`. +- `export-surface.ps1` + - Generates Markdown documents for both the cmdlet surface and the model (class) surface of the module. + - These files are placed into the `resources` folder. + - Used for investigating the surface of your module. These are *not* documentation for distribution. +- `check-dependencies.ps1` + - Used in `run-module.ps1` and `test-module.ps1` to verify dependent modules are available to run those tasks. + - It will download local (within the module's directory structure) versions of those modules as needed. + - This script *does not* need to be ran by-hand. \ No newline at end of file diff --git a/src/AppConfiguration/internal/Az.AppConfiguration.internal.psm1 b/src/AppConfiguration/internal/Az.AppConfiguration.internal.psm1 new file mode 100644 index 000000000000..96df43fa9fea --- /dev/null +++ b/src/AppConfiguration/internal/Az.AppConfiguration.internal.psm1 @@ -0,0 +1,38 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.AppConfiguration.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Module]::Instance + + # Export nothing to clear implicit exports + Export-ModuleMember + + # Export proxy cmdlet scripts + $exportsPath = $PSScriptRoot + $directories = Get-ChildItem -Directory -Path $exportsPath + $profileDirectory = $null + if($instance.ProfileName) { + if(($directories | ForEach-Object { $_.Name }) -contains $instance.ProfileName) { + $profileDirectory = $directories | Where-Object { $_.Name -eq $instance.ProfileName } + } else { + # Don't export anything if the profile doesn't exist for the module + $exportsPath = $null + Write-Warning "Selected Azure profile '$($instance.ProfileName)' does not exist for module '$($instance.Name)'. No cmdlets were loaded." + } + } elseif(($directories | Measure-Object).Count -gt 0) { + # Load the last folder if no profile is selected + $profileDirectory = $directories | Select-Object -Last 1 + } + + if($profileDirectory) { + Write-Information "Loaded Azure profile '$($profileDirectory.Name)' for module '$($instance.Name)'" + $exportsPath = $profileDirectory.FullName + } + + if($exportsPath) { + Get-ChildItem -Path $exportsPath -Recurse -Include '*.ps1' -File | ForEach-Object { . $_.FullName } + $cmdletNames = Get-ScriptCmdlet -ScriptFolder $exportsPath + Export-ModuleMember -Function $cmdletNames -Alias (Get-ScriptCmdlet -ScriptFolder $exportsPath -AsAlias) + } +# endregion diff --git a/src/AppConfiguration/internal/Get-AzAppConfigurationOperation.ps1 b/src/AppConfiguration/internal/Get-AzAppConfigurationOperation.ps1 new file mode 100644 index 000000000000..8b356efa7c36 --- /dev/null +++ b/src/AppConfiguration/internal/Get-AzAppConfigurationOperation.ps1 @@ -0,0 +1,128 @@ + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Lists the operations available from this provider. +.Description +Lists the operations available from this provider. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/get-azappconfigurationoperation +#> +function Get-AzAppConfigurationOperation { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Query')] + [System.String] + # A skip token is used to continue retrieving items after an operation returns a partial result. + # If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. + ${SkipToken}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + List = 'Az.AppConfiguration.private\Get-AzAppConfigurationOperation_List'; + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/AppConfiguration/internal/New-AzAppConfigurationStore.ps1 b/src/AppConfiguration/internal/New-AzAppConfigurationStore.ps1 new file mode 100644 index 000000000000..dab1f5d2c523 --- /dev/null +++ b/src/AppConfiguration/internal/New-AzAppConfigurationStore.ps1 @@ -0,0 +1,189 @@ + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates a configuration store with the specified parameters. +.Description +Creates a configuration store with the specified parameters. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +CONFIGSTORECREATIONPARAMETER : The configuration store along with all resource properties. The Configuration Store will have all information to begin utilizing it. + Location : The location of the resource. This cannot be changed after the resource is created. + [Tag ]: The tags of the resource. + [(Any) ]: This indicates any property can be added to this object. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/new-azappconfigurationstore +#> +function New-AzAppConfigurationStore { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore])] +[CmdletBinding(DefaultParameterSetName='CreateViaIdentity', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Create', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(ParameterSetName='Create', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Create')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='CreateViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter(Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore] + # The configuration store along with all resource properties. + # The Configuration Store will have all information to begin utilizing it. + # To construct, see NOTES section for CONFIGSTORECREATIONPARAMETER properties and create a hash table. + ${ConfigStoreCreationParameter}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Create = 'Az.AppConfiguration.private\New-AzAppConfigurationStore_Create'; + CreateViaIdentity = 'Az.AppConfiguration.private\New-AzAppConfigurationStore_CreateViaIdentity'; + } + if (('Create') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/AppConfiguration/internal/New-AzAppConfigurationStoreKey.ps1 b/src/AppConfiguration/internal/New-AzAppConfigurationStoreKey.ps1 new file mode 100644 index 000000000000..c6d67325b216 --- /dev/null +++ b/src/AppConfiguration/internal/New-AzAppConfigurationStoreKey.ps1 @@ -0,0 +1,174 @@ + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Regenerates an access key for the specified configuration store. +.Description +Regenerates an access key for the specified configuration store. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. + +REGENERATEKEYPARAMETER : The parameters used to regenerate an API key. + [Id ]: The id of the key to regenerate. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/new-azappconfigurationstorekey +#> +function New-AzAppConfigurationStoreKey { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey])] +[CmdletBinding(DefaultParameterSetName='RegenerateViaIdentity', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Regenerate', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(ParameterSetName='Regenerate', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Regenerate')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='RegenerateViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter(Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters] + # The parameters used to regenerate an API key. + # To construct, see NOTES section for REGENERATEKEYPARAMETER properties and create a hash table. + ${RegenerateKeyParameter}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Regenerate = 'Az.AppConfiguration.private\New-AzAppConfigurationStoreKey_Regenerate'; + RegenerateViaIdentity = 'Az.AppConfiguration.private\New-AzAppConfigurationStoreKey_RegenerateViaIdentity'; + } + if (('Regenerate') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/AppConfiguration/internal/ProxyCmdletDefinitions.ps1 b/src/AppConfiguration/internal/ProxyCmdletDefinitions.ps1 new file mode 100644 index 000000000000..310bafe16d9b --- /dev/null +++ b/src/AppConfiguration/internal/ProxyCmdletDefinitions.ps1 @@ -0,0 +1,863 @@ + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Lists the operations available from this provider. +.Description +Lists the operations available from this provider. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/get-azappconfigurationoperation +#> +function Get-AzAppConfigurationOperation { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IOperationDefinition])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Query')] + [System.String] + # A skip token is used to continue retrieving items after an operation returns a partial result. + # If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. + ${SkipToken}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + List = 'Az.AppConfiguration.private\Get-AzAppConfigurationOperation_List'; + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Regenerates an access key for the specified configuration store. +.Description +Regenerates an access key for the specified configuration store. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. + +REGENERATEKEYPARAMETER : The parameters used to regenerate an API key. + [Id ]: The id of the key to regenerate. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/new-azappconfigurationstorekey +#> +function New-AzAppConfigurationStoreKey { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IApiKey])] +[CmdletBinding(DefaultParameterSetName='RegenerateViaIdentity', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Regenerate', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(ParameterSetName='Regenerate', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Regenerate')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='RegenerateViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter(Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IRegenerateKeyParameters] + # The parameters used to regenerate an API key. + # To construct, see NOTES section for REGENERATEKEYPARAMETER properties and create a hash table. + ${RegenerateKeyParameter}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Regenerate = 'Az.AppConfiguration.private\New-AzAppConfigurationStoreKey_Regenerate'; + RegenerateViaIdentity = 'Az.AppConfiguration.private\New-AzAppConfigurationStoreKey_RegenerateViaIdentity'; + } + if (('Regenerate') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates a configuration store with the specified parameters. +.Description +Creates a configuration store with the specified parameters. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +CONFIGSTORECREATIONPARAMETER : The configuration store along with all resource properties. The Configuration Store will have all information to begin utilizing it. + Location : The location of the resource. This cannot be changed after the resource is created. + [Tag ]: The tags of the resource. + [(Any) ]: This indicates any property can be added to this object. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/new-azappconfigurationstore +#> +function New-AzAppConfigurationStore { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore])] +[CmdletBinding(DefaultParameterSetName='CreateViaIdentity', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Create', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(ParameterSetName='Create', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Create')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='CreateViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter(Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore] + # The configuration store along with all resource properties. + # The Configuration Store will have all information to begin utilizing it. + # To construct, see NOTES section for CONFIGSTORECREATIONPARAMETER properties and create a hash table. + ${ConfigStoreCreationParameter}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Create = 'Az.AppConfiguration.private\New-AzAppConfigurationStore_Create'; + CreateViaIdentity = 'Az.AppConfiguration.private\New-AzAppConfigurationStore_CreateViaIdentity'; + } + if (('Create') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Checks whether the configuration store name is available for use. +.Description +Checks whether the configuration store name is available for use. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +CHECKNAMEAVAILABILITYPARAMETER : Parameters used for checking whether a resource name is available. + Name : The name to check for availability. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/test-azappconfigurationstorenameavailability +#> +function Test-AzAppConfigurationStoreNameAvailability { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus])] +[CmdletBinding(DefaultParameterSetName='Check', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Check')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='CheckViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter(Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters] + # Parameters used for checking whether a resource name is available. + # To construct, see NOTES section for CHECKNAMEAVAILABILITYPARAMETER properties and create a hash table. + ${CheckNameAvailabilityParameter}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Check = 'Az.AppConfiguration.private\Test-AzAppConfigurationStoreNameAvailability_Check'; + CheckViaIdentity = 'Az.AppConfiguration.private\Test-AzAppConfigurationStoreNameAvailability_CheckViaIdentity'; + } + if (('Check') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Updates a configuration store with the specified parameters. +.Description +Updates a configuration store with the specified parameters. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +CONFIGSTOREUPDATEPARAMETER : The parameters for updating a configuration store. + [Property ]: The properties for updating a configuration store. + [Tag ]: The ARM resource tags. + [(Any) ]: This indicates any property can be added to this object. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/update-azappconfigurationstore +#> +function Update-AzAppConfigurationStore { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Update', Mandatory)] + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(ParameterSetName='Update', Mandatory)] + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Update')] + [Parameter(ParameterSetName='UpdateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentity', Mandatory, ValueFromPipeline)] + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter(ParameterSetName='Update', Mandatory, ValueFromPipeline)] + [Parameter(ParameterSetName='UpdateViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters] + # The parameters for updating a configuration store. + # To construct, see NOTES section for CONFIGSTOREUPDATEPARAMETER properties and create a hash table. + ${ConfigStoreUpdateParameter}, + + [Parameter(ParameterSetName='UpdateExpanded')] + [Parameter(ParameterSetName='UpdateViaIdentityExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters] + # The properties for updating a configuration store. + ${Property}, + + [Parameter(ParameterSetName='UpdateExpanded')] + [Parameter(ParameterSetName='UpdateViaIdentityExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags]))] + [System.Collections.Hashtable] + # The ARM resource tags. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Update = 'Az.AppConfiguration.private\Update-AzAppConfigurationStore_Update'; + UpdateExpanded = 'Az.AppConfiguration.private\Update-AzAppConfigurationStore_UpdateExpanded'; + UpdateViaIdentity = 'Az.AppConfiguration.private\Update-AzAppConfigurationStore_UpdateViaIdentity'; + UpdateViaIdentityExpanded = 'Az.AppConfiguration.private\Update-AzAppConfigurationStore_UpdateViaIdentityExpanded'; + } + if (('Update', 'UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/AppConfiguration/internal/Test-AzAppConfigurationStoreNameAvailability.ps1 b/src/AppConfiguration/internal/Test-AzAppConfigurationStoreNameAvailability.ps1 new file mode 100644 index 000000000000..3159069b7a31 --- /dev/null +++ b/src/AppConfiguration/internal/Test-AzAppConfigurationStoreNameAvailability.ps1 @@ -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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Checks whether the configuration store name is available for use. +.Description +Checks whether the configuration store name is available for use. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +CHECKNAMEAVAILABILITYPARAMETER : Parameters used for checking whether a resource name is available. + Name : The name to check for availability. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/test-azappconfigurationstorenameavailability +#> +function Test-AzAppConfigurationStoreNameAvailability { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.INameAvailabilityStatus])] +[CmdletBinding(DefaultParameterSetName='Check', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Check')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='CheckViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter(Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.ICheckNameAvailabilityParameters] + # Parameters used for checking whether a resource name is available. + # To construct, see NOTES section for CHECKNAMEAVAILABILITYPARAMETER properties and create a hash table. + ${CheckNameAvailabilityParameter}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Check = 'Az.AppConfiguration.private\Test-AzAppConfigurationStoreNameAvailability_Check'; + CheckViaIdentity = 'Az.AppConfiguration.private\Test-AzAppConfigurationStoreNameAvailability_CheckViaIdentity'; + } + if (('Check') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/AppConfiguration/internal/Update-AzAppConfigurationStore.ps1 b/src/AppConfiguration/internal/Update-AzAppConfigurationStore.ps1 new file mode 100644 index 000000000000..717ea285219b --- /dev/null +++ b/src/AppConfiguration/internal/Update-AzAppConfigurationStore.ps1 @@ -0,0 +1,210 @@ + +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Updates a configuration store with the specified parameters. +.Description +Updates a configuration store with the specified parameters. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore +.Notes +COMPLEX PARAMETER PROPERTIES +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +CONFIGSTOREUPDATEPARAMETER : The parameters for updating a configuration store. + [Property ]: The properties for updating a configuration store. + [Tag ]: The ARM resource tags. + [(Any) ]: This indicates any property can be added to this object. + +INPUTOBJECT : Identity Parameter + [ConfigStoreName ]: The name of the configuration store. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group to which the container registry belongs. + [SubscriptionId ]: The Microsoft Azure subscription ID. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.appconfiguration/update-azappconfigurationstore +#> +function Update-AzAppConfigurationStore { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStore])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Update', Mandatory)] + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the configuration store. + ${Name}, + + [Parameter(ParameterSetName='Update', Mandatory)] + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [System.String] + # The name of the resource group to which the container registry belongs. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Update')] + [Parameter(ParameterSetName='UpdateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Microsoft Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentity', Mandatory, ValueFromPipeline)] + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.IAppConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter(ParameterSetName='Update', Mandatory, ValueFromPipeline)] + [Parameter(ParameterSetName='UpdateViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParameters] + # The parameters for updating a configuration store. + # To construct, see NOTES section for CONFIGSTOREUPDATEPARAMETER properties and create a hash table. + ${ConfigStoreUpdateParameter}, + + [Parameter(ParameterSetName='UpdateExpanded')] + [Parameter(ParameterSetName='UpdateViaIdentityExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStorePropertiesUpdateParameters] + # The properties for updating a configuration store. + ${Property}, + + [Parameter(ParameterSetName='UpdateExpanded')] + [Parameter(ParameterSetName='UpdateViaIdentityExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Models.Api20190201Preview.IConfigurationStoreUpdateParametersTags]))] + [System.Collections.Hashtable] + # The ARM resource tags. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.AppConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Update = 'Az.AppConfiguration.private\Update-AzAppConfigurationStore_Update'; + UpdateExpanded = 'Az.AppConfiguration.private\Update-AzAppConfigurationStore_UpdateExpanded'; + UpdateViaIdentity = 'Az.AppConfiguration.private\Update-AzAppConfigurationStore_UpdateViaIdentity'; + UpdateViaIdentityExpanded = 'Az.AppConfiguration.private\Update-AzAppConfigurationStore_UpdateViaIdentityExpanded'; + } + if (('Update', 'UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/AppConfiguration/internal/readme.md b/src/AppConfiguration/internal/readme.md new file mode 100644 index 000000000000..49d26de9c732 --- /dev/null +++ b/src/AppConfiguration/internal/readme.md @@ -0,0 +1,14 @@ +# Internal +This directory contains a module to handle *internal only* cmdlets. Cmdlets that you **hide** in configuration are created here. For more information on hiding, see [cmdlet hiding](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md#cmdlet-hiding-exportation-suppression). The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The `Az.AppConfiguration.internal.psm1` file is generated to this folder. This module file handles the hidden cmdlets. These cmdlets will not be exported by `Az.AppConfiguration`. Instead, this sub-module is imported by the `..\custom\Az.AppConfiguration.custom.psm1` module, allowing you to use hidden cmdlets in your custom, exposed cmdlets. To call these cmdlets in your custom scripts, simply use [module-qualified calls](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_command_precedence?view=powershell-6#qualified-names). For example, `Az.AppConfiguration.internal\Get-Example` would call an internal cmdlet named `Get-Example`. + +## Purpose +This allows you to include REST specifications for services that you *do not wish to expose from your module*, but simply want to call within custom cmdlets. For example, if you want to make a custom cmdlet that uses `Storage` services, you could include a simplified `Storage` REST specification that has only the operations you need. When you run the generator and build this module, note the generated `Storage` cmdlets. Then, in your readme configuration, use [cmdlet hiding](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md#cmdlet-hiding-exportation-suppression) on the `Storage` cmdlets and they will *only be exposed to the custom cmdlets* you want to write, and not be exported as part of `Az.AppConfiguration`. \ No newline at end of file diff --git a/src/AppConfiguration/pack-module.ps1 b/src/AppConfiguration/pack-module.ps1 new file mode 100644 index 000000000000..c22fad33d87b --- /dev/null +++ b/src/AppConfiguration/pack-module.ps1 @@ -0,0 +1,16 @@ +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- +Write-Host -ForegroundColor Green 'Packing module...' +dotnet pack $PSScriptRoot --no-build /nologo +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/AppConfiguration/readme.md b/src/AppConfiguration/readme.md new file mode 100644 index 000000000000..c57e9a093f22 --- /dev/null +++ b/src/AppConfiguration/readme.md @@ -0,0 +1,79 @@ + +# Az.AppConfiguration +This directory contains the PowerShell module for the AppConfiguration service. + +--- +## Status +[![Az.AppConfiguration](https://img.shields.io/powershellgallery/v/Az.AppConfiguration.svg?style=flat-square&label=Az.AppConfiguration "Az.AppConfiguration")](https://www.powershellgallery.com/packages/Az.AppConfiguration/) + +## Info +- Modifiable: yes +- Generated: all +- Committed: yes +- Packaged: yes + +--- +## Detail +This module was primarily generated via [AutoRest](https://github.com/Azure/autorest) using the [PowerShell](https://github.com/Azure/autorest.powershell) extension. + +## Module Requirements +- [Az.Accounts module](https://www.powershellgallery.com/packages/Az.Accounts/), version 1.7.4 or greater + +## Authentication +AutoRest does not generate authentication code for the module. Authentication is handled via Az.Accounts by altering the HTTP payload before it is sent. + +## Development +For information on how to develop for `Az.AppConfiguration`, see [how-to.md](how-to.md). + + +--- +## Generation Requirements +Use of the beta version of `autorest.powershell` generator requires the following: +- [NodeJS LTS](https://nodejs.org) (10.15.x LTS preferred) + - **Note**: It *will not work* with Node < 10.x. Using 11.x builds may cause issues as they may introduce instability or breaking changes. +> If you want an easy way to install and update Node, [NVS - Node Version Switcher](../nodejs/installing-via-nvs.md) or [NVM - Node Version Manager](../nodejs/installing-via-nvm.md) is recommended. +- [AutoRest](https://aka.ms/autorest) v3 beta
`npm install -g autorest@beta`
  +- PowerShell 6.0 or greater + - If you don't have it installed, you can use the cross-platform npm package
`npm install -g pwsh`
  +- .NET Core SDK 2.0 or greater + - If you don't have it installed, you can use the cross-platform npm package
`npm install -g dotnet-sdk-2.2`
  + +## Run Generation +In this directory, run AutoRest: +> `autorest` + +--- +### AutoRest Configuration +> see https://aka.ms/autorest + +``` yaml +require: + - $(this-folder)/../readme.azure.noprofile.md +input-file: + - $(repo)/specification/appconfiguration/resource-manager/Microsoft.AppConfiguration/preview/2019-02-01-preview/appconfiguration.json + #- $(repo)/specification/appconfiguration/resource-manager/Microsoft.AppConfiguration/stable/2019-10-01/appconfiguration.json + +module-version: 0.1.4 + +directive: + - where: + parameter-name: ConfigStoreCreationParameter|RegenerateKeyParameter|CheckNameAvailabilityParameter + select: command + hide: true + - where: + verb: Update + subject: ConfigurationStore + hide: true + - where: + parameter-name: ConfigStoreName + set: + parameter-name: Name + - where: + subject: OperationNameAvailability + set: + subject: StoreNameAvailability + - where: + subject: ConfigurationStoreKeyValue + verb: Get + remove: true +``` diff --git a/src/AppConfiguration/run-module.ps1 b/src/AppConfiguration/run-module.ps1 new file mode 100644 index 000000000000..099067839134 --- /dev/null +++ b/src/AppConfiguration/run-module.ps1 @@ -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. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Code) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$isAzure = $true +if($isAzure) { + . (Join-Path $PSScriptRoot 'check-dependencies.ps1') -Isolated -Accounts +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.AppConfiguration.psd1') +$modulePath = $modulePsd1.FullName +$moduleName = $modulePsd1.BaseName + +function Prompt { + Write-Host -NoNewline -ForegroundColor Green "PS $(Get-Location)" + Write-Host -NoNewline -ForegroundColor Gray ' [' + Write-Host -NoNewline -ForegroundColor White -BackgroundColor DarkCyan $moduleName + ']> ' +} + +# where we would find the launch.json file +$vscodeDirectory = New-Item -ItemType Directory -Force -Path (Join-Path $PSScriptRoot '.vscode') +$launchJson = Join-Path $vscodeDirectory 'launch.json' + +# if there is a launch.json file, let's just assume -Code, and update the file +if(($Code) -or (test-Path $launchJson) ) { + $launchContent = '{ "version": "0.2.0", "configurations":[{ "name":"Attach to PowerShell", "type":"coreclr", "request":"attach", "processId":"' + ([System.Diagnostics.Process]::GetCurrentProcess().Id) + '", "justMyCode":false }] }' + Set-Content -Path $launchJson -Value $launchContent + if($Code) { + # only launch vscode if they say -code + code $PSScriptRoot + } +} + +Import-Module -Name $modulePath \ No newline at end of file diff --git a/src/AppConfiguration/test-module.ps1 b/src/AppConfiguration/test-module.ps1 new file mode 100644 index 000000000000..5c44bf64c148 --- /dev/null +++ b/src/AppConfiguration/test-module.ps1 @@ -0,0 +1,68 @@ +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Live, [switch]$Record, [switch]$Playback) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$ProgressPreference = 'SilentlyContinue' +$baseName = $PSScriptRoot.BaseName +$requireResourceModule = (($baseName -ne "Resources") -and ($Record.IsPresent -or $Live.IsPresent)) +. (Join-Path $PSScriptRoot 'check-dependencies.ps1') -Isolated -Accounts:$false -Pester -Resources:$requireResourceModule +. ("$PSScriptRoot\test\utils.ps1") + +if ($requireResourceModule) { + $resourceModulePSD = Get-Item -Path (Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psd1') + Import-Module -Name $resourceModulePSD.FullName +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.AppConfiguration.psd1') +$modulePath = $modulePsd1.FullName +$moduleName = $modulePsd1.BaseName + +Import-Module -Name Pester +Import-Module -Name $modulePath + +$TestMode = 'playback' +if($Live) { + $TestMode = 'live' +} +if($Record) { + $TestMode = 'record' +} +try { + if ($TestMode -ne 'playback') { + setupEnv + } + $testFolder = Join-Path $PSScriptRoot 'test' + Invoke-Pester -Script @{ Path = $testFolder } -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") +} +Finally +{ + if ($TestMode -ne 'playback') { + cleanupEnv + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/AppConfiguration/test/Az.AppConfiguration-TestResults.xml b/src/AppConfiguration/test/Az.AppConfiguration-TestResults.xml new file mode 100644 index 000000000000..f123ddf1d1c7 --- /dev/null +++ b/src/AppConfiguration/test/Az.AppConfiguration-TestResults.xml @@ -0,0 +1,106 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Expected no exception to be thrown, but an exception "System.NotImplementedException" was thrown from C:\Users\xidi\src\azure-powershell\src\AppConfiguration\test\Update-AzAppConfigurationStore.Tests.ps1:5 char:11 + + { throw [System.NotImplementedException] } | Should -Not -Thr ... + + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~. + at <ScriptBlock>, C:\Users\xidi\src\azure-powershell\src\AppConfiguration\test\Update-AzAppConfigurationStore.Tests.ps1: line 5 +5: { throw [System.NotImplementedException] } | Should -Not -Throw + + + + + Expected no exception to be thrown, but an exception "System.NotImplementedException" was thrown from C:\Users\xidi\src\azure-powershell\src\AppConfiguration\test\Update-AzAppConfigurationStore.Tests.ps1:9 char:11 + + { throw [System.NotImplementedException] } | Should -Not -Thr ... + + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~. + at <ScriptBlock>, C:\Users\xidi\src\azure-powershell\src\AppConfiguration\test\Update-AzAppConfigurationStore.Tests.ps1: line 9 +9: { throw [System.NotImplementedException] } | Should -Not -Throw + + + + + + + + + \ No newline at end of file diff --git a/src/AppConfiguration/test/Get-AzAppConfigurationStore.Tests.ps1 b/src/AppConfiguration/test/Get-AzAppConfigurationStore.Tests.ps1 new file mode 100644 index 000000000000..a29bd9759953 --- /dev/null +++ b/src/AppConfiguration/test/Get-AzAppConfigurationStore.Tests.ps1 @@ -0,0 +1,30 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Get-AzAppConfigurationStore.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'Get-AzAppConfigurationStore' { + It 'List' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } + + It 'Get' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } + + It 'List1' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } + + It 'GetViaIdentity' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } +} diff --git a/src/AppConfiguration/test/Get-AzAppConfigurationStoreKey.Tests.ps1 b/src/AppConfiguration/test/Get-AzAppConfigurationStoreKey.Tests.ps1 new file mode 100644 index 000000000000..e42ec3d3f0b4 --- /dev/null +++ b/src/AppConfiguration/test/Get-AzAppConfigurationStoreKey.Tests.ps1 @@ -0,0 +1,18 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Get-AzAppConfigurationStoreKey.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'Get-AzAppConfigurationStoreKey' { + It 'List' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } +} diff --git a/src/AppConfiguration/test/New-AzAppConfigurationStore.Tests.ps1 b/src/AppConfiguration/test/New-AzAppConfigurationStore.Tests.ps1 new file mode 100644 index 000000000000..719f563e2c63 --- /dev/null +++ b/src/AppConfiguration/test/New-AzAppConfigurationStore.Tests.ps1 @@ -0,0 +1,22 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'New-AzAppConfigurationStore.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'New-AzAppConfigurationStore' { + It 'CreateExpanded' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } + + It 'CreateViaIdentityExpanded' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } +} diff --git a/src/AppConfiguration/test/New-AzAppConfigurationStoreKey.Tests.ps1 b/src/AppConfiguration/test/New-AzAppConfigurationStoreKey.Tests.ps1 new file mode 100644 index 000000000000..a51dd4f5a5e4 --- /dev/null +++ b/src/AppConfiguration/test/New-AzAppConfigurationStoreKey.Tests.ps1 @@ -0,0 +1,22 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'New-AzAppConfigurationStoreKey.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'New-AzAppConfigurationStoreKey' { + It 'RegenerateExpanded' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } + + It 'RegenerateViaIdentityExpanded' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } +} diff --git a/src/AppConfiguration/test/Remove-AzAppConfigurationStore.Tests.ps1 b/src/AppConfiguration/test/Remove-AzAppConfigurationStore.Tests.ps1 new file mode 100644 index 000000000000..a594f187ee72 --- /dev/null +++ b/src/AppConfiguration/test/Remove-AzAppConfigurationStore.Tests.ps1 @@ -0,0 +1,22 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Remove-AzAppConfigurationStore.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'Remove-AzAppConfigurationStore' { + It 'Delete' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } + + It 'DeleteViaIdentity' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } +} diff --git a/src/AppConfiguration/test/Test-AzAppConfigurationStoreNameAvailability.Tests.ps1 b/src/AppConfiguration/test/Test-AzAppConfigurationStoreNameAvailability.Tests.ps1 new file mode 100644 index 000000000000..1f7f45c5b8af --- /dev/null +++ b/src/AppConfiguration/test/Test-AzAppConfigurationStoreNameAvailability.Tests.ps1 @@ -0,0 +1,22 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Test-AzAppConfigurationStoreNameAvailability.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'Test-AzAppConfigurationStoreNameAvailability' { + It 'CheckExpanded' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } + + It 'CheckViaIdentityExpanded' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } +} diff --git a/src/AppConfiguration/test/Update-AzAppConfigurationStore.Tests.ps1 b/src/AppConfiguration/test/Update-AzAppConfigurationStore.Tests.ps1 new file mode 100644 index 000000000000..31b80ea50ce0 --- /dev/null +++ b/src/AppConfiguration/test/Update-AzAppConfigurationStore.Tests.ps1 @@ -0,0 +1,11 @@ +. (Join-Path $PSScriptRoot '..\generated\runtime' 'HttpPipelineMocking.ps1') + +Describe 'Update-AzAppConfigurationStore' { + It 'UpdateExpanded' { + { throw [System.NotImplementedException] } | Should -Not -Throw + } + + It 'UpdateViaIdentityExpanded' { + { throw [System.NotImplementedException] } | Should -Not -Throw + } +} diff --git a/src/AppConfiguration/test/loadEnv.ps1 b/src/AppConfiguration/test/loadEnv.ps1 new file mode 100644 index 000000000000..c4ebf2e8310c --- /dev/null +++ b/src/AppConfiguration/test/loadEnv.ps1 @@ -0,0 +1,28 @@ +# ---------------------------------------------------------------------------------- +# +# 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. +# ---------------------------------------------------------------------------------- +$envFile = 'env.json' +if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' +} + +if (Test-Path -Path (Join-Path $PSScriptRoot $envFile)) { + $envFilePath = Join-Path $PSScriptRoot $envFile +} else { + $envFilePath = Join-Path $PSScriptRoot '..\$envFile' +} +$env = @{} +if (Test-Path -Path $envFilePath) { + $env = Get-Content (Join-Path $PSScriptRoot $envFile) | ConvertFrom-Json + $PSDefaultParameterValues=@{"*:SubscriptionId"=$env.SubscriptionId; "*:Tenant"=$env.Tenant} +} \ No newline at end of file diff --git a/src/AppConfiguration/test/readme.md b/src/AppConfiguration/test/readme.md new file mode 100644 index 000000000000..7c752b4c8c43 --- /dev/null +++ b/src/AppConfiguration/test/readme.md @@ -0,0 +1,17 @@ +# Test +This directory contains the [Pester](https://www.powershellgallery.com/packages/Pester) tests to run for the module. We use Pester as it is the unofficial standard for PowerShell unit testing. Test stubs for custom cmdlets (created in `..\custom`) will be generated into this folder when `build-module.ps1` is ran. These test stubs will fail automatically, to indicate that tests should be written for custom cmdlets. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: no + +## Details +We allow three testing modes: *live*, *record*, and *playback*. These can be selected using the `-Live`, `-Record`, and `-Playback` switches respectively on the `test-module.ps1` script. This script will run through any `.Tests.ps1` scripts in the `test` folder. If you choose the *record* mode, it will create a `.Recording.json` file of the REST calls between the client and server. Then, when you choose *playback* mode, it will use the `.Recording.json` file to mock the communication between server and client. The *live* mode runs the same as the *record* mode; however, it doesn't create the `.Recording.json` file. + +## Purpose +Custom cmdlets generally encompass additional functionality not described in the REST specification, or combines functionality generated from the REST spec. To validate this functionality continues to operate as intended, creating tests that can be ran and re-ran against custom cmdlets is part of the framework. + +## Usage +To execute tests, run the `test-module.ps1`. To write tests, [this example](https://github.com/pester/Pester/blob/8b9cf4248315e44f1ac6673be149f7e0d7f10466/Examples/Planets/Get-Planet.Tests.ps1#L1) from the Pester repository is very useful for getting started. \ No newline at end of file diff --git a/src/AppConfiguration/test/utils.ps1 b/src/AppConfiguration/test/utils.ps1 new file mode 100644 index 000000000000..8876c288462c --- /dev/null +++ b/src/AppConfiguration/test/utils.ps1 @@ -0,0 +1,24 @@ +function RandomString([bool]$allChars, [int32]$len) { + if ($allChars) { + return -join ((33..126) | Get-Random -Count $len | % {[char]$_}) + } else { + return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_}) + } +} +$env = @{} +function setupEnv() { + # Preload subscriptionId and tenant from context, which will be used in test + # as default. You could change them if needed. + $env.SubscriptionId = (Get-AzContext).Subscription.Id + $env.Tenant = (Get-AzContext).Tenant.Id + # For any resources you created for test, you should add it to $env here. + $envFile = 'env.json' + if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' + } + set-content -Path (Join-Path $PSScriptRoot $envFile) -Value (ConvertTo-Json $env) +} +function cleanupEnv() { + # Clean resources you create for testing +} + diff --git a/tools/CreateMappings_rules.json b/tools/CreateMappings_rules.json index 7ed504df8076..25ff345a9378 100644 --- a/tools/CreateMappings_rules.json +++ b/tools/CreateMappings_rules.json @@ -167,5 +167,6 @@ { "regex": "Databricks", "alias": "Databricks" }, { "regex": "MariaDb", "alias": "MariaDb" }, { "regex": "MySql", "alias": "MySql" }, + { "regex": "AppConfiguration", "alias": "App Configuration" }, { "regex": "StackEdge", "alias": "Stack Edge" } ] diff --git a/tools/GenerateHelp.ps1 b/tools/GenerateHelp.ps1 index e0caa418bf8a..16d4c9842e91 100644 --- a/tools/GenerateHelp.ps1 +++ b/tools/GenerateHelp.ps1 @@ -79,7 +79,8 @@ if ($ValidateMarkdownHelp) } # We need to define new version of module instead of hardcode here -$NewModules = @("Az.Databricks", +$NewModules = @("Az.AppConfiguration", + "Az.Databricks", "Az.MySql", "Az.MariaDb" )