diff --git a/src/Resources/Authorization.Autorest/Az.Authorization.psd1 b/src/Resources/Authorization.Autorest/Az.Authorization.psd1 index 5b2d5a563e60..884537d5f28b 100644 --- a/src/Resources/Authorization.Autorest/Az.Authorization.psd1 +++ b/src/Resources/Authorization.Autorest/Az.Authorization.psd1 @@ -1,5 +1,5 @@ @{ - GUID = '57a55527-7087-451e-84e4-04cf34c3f59d' + GUID = 'de90936a-b512-40d3-93cd-aa8c85077b04' RootModule = './Az.Authorization.psm1' ModuleVersion = '0.1.0' CompatiblePSEditions = 'Core', 'Desktop' diff --git a/src/Resources/Authorization.Autorest/help/Az.Authorization.md b/src/Resources/Authorization.Autorest/help/Az.Authorization.md index a2373f3af6a4..e883558be77e 100644 --- a/src/Resources/Authorization.Autorest/help/Az.Authorization.md +++ b/src/Resources/Authorization.Autorest/help/Az.Authorization.md @@ -1,6 +1,6 @@ --- Module Name: Az.Authorization -Module Guid: 57a55527-7087-451e-84e4-04cf34c3f59d +Module Guid: de90936a-b512-40d3-93cd-aa8c85077b04 Download Help Link: https://learn.microsoft.com/powershell/module/az.authorization Help Version: 1.0.0.0 Locale: en-US diff --git a/src/Resources/DataBoundary.Autorest/Az.DataBoundary.csproj b/src/Resources/DataBoundary.Autorest/Az.DataBoundary.csproj new file mode 100644 index 000000000000..dacb803e258e --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/Az.DataBoundary.csproj @@ -0,0 +1,10 @@ + + + DataBoundary + Resources + DataBoundary.Autorest + + + + + diff --git a/src/Resources/DataBoundary.Autorest/Az.DataBoundary.format.ps1xml b/src/Resources/DataBoundary.Autorest/Az.DataBoundary.format.ps1xml new file mode 100644 index 000000000000..2c21ce95f9bb --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/Az.DataBoundary.format.ps1xml @@ -0,0 +1,393 @@ + + + + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryDefinition + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryDefinition#Multiple + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Name + + + SystemDataCreatedAt + + + SystemDataCreatedBy + + + SystemDataCreatedByType + + + SystemDataLastModifiedAt + + + SystemDataLastModifiedBy + + + SystemDataLastModifiedByType + + + ResourceGroupName + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryIdentity + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryIdentity#Multiple + + + + + + + + + + + + + + + Default + + + Scope + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryProperties + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryProperties#Multiple + + + + + + + + + + + + + + + DataBoundary + + + ProvisioningState + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorDetail + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorDetail#Multiple + + + + + + + + + + + + + + + + + + Code + + + Message + + + Target + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.Operation + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.Operation#Multiple + + + + + + + + + + + + + + + + + + + + + ActionType + + + IsDataAction + + + Name + + + Origin + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.OperationDisplay + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.OperationDisplay#Multiple + + + + + + + + + + + + + + + + + + + + + Description + + + Operation + + + Provider + + + Resource + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.OperationListResult + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.OperationListResult#Multiple + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ProxyResource + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ProxyResource#Multiple + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Name + + + SystemDataCreatedAt + + + SystemDataCreatedBy + + + SystemDataCreatedByType + + + SystemDataLastModifiedAt + + + SystemDataLastModifiedBy + + + SystemDataLastModifiedByType + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.Resource + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.Resource#Multiple + + + + + + + + + + + + Name + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.SystemData + + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.SystemData#Multiple + + + + + + + + + + + + + + + + + + + + + + + + + + + CreatedAt + + + CreatedBy + + + CreatedByType + + + LastModifiedAt + + + LastModifiedBy + + + LastModifiedByType + + + + + + + + \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/Az.DataBoundary.psd1 b/src/Resources/DataBoundary.Autorest/Az.DataBoundary.psd1 new file mode 100644 index 000000000000..8a62b91823b4 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/Az.DataBoundary.psd1 @@ -0,0 +1,23 @@ +@{ + GUID = 'c0d70364-96af-43cf-a3ca-76edff8b31b7' + RootModule = './Az.DataBoundary.psm1' + ModuleVersion = '0.1.1' + CompatiblePSEditions = 'Core', 'Desktop' + Author = 'Microsoft Corporation' + CompanyName = 'Microsoft Corporation' + Copyright = 'Microsoft Corporation. All rights reserved.' + Description = 'Microsoft Azure PowerShell: DataBoundary cmdlets' + PowerShellVersion = '5.1' + DotNetFrameworkVersion = '4.7.2' + RequiredAssemblies = './bin/Az.DataBoundary.private.dll' + FormatsToProcess = './Az.DataBoundary.format.ps1xml' + FunctionsToExport = 'Get-AzDataBoundaryScope', 'Get-AzDataBoundaryTenant', 'Set-AzDataBoundary' + PrivateData = @{ + PSData = @{ + Tags = 'Azure', 'ResourceManager', 'ARM', 'PSModule', 'DataBoundary' + LicenseUri = 'https://aka.ms/azps-license' + ProjectUri = 'https://github.com/Azure/azure-powershell' + ReleaseNotes = '' + } + } +} diff --git a/src/Resources/DataBoundary.Autorest/Az.DataBoundary.psm1 b/src/Resources/DataBoundary.Autorest/Az.DataBoundary.psm1 new file mode 100644 index 000000000000..ef02247e7676 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/Az.DataBoundary.psm1 @@ -0,0 +1,119 @@ +# region Generated + # ---------------------------------------------------------------------------------- + # Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. + # ---------------------------------------------------------------------------------- + # 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]'2.7.5' } | Measure-Object).Count -gt 0 + if($hasAdequateVersion) { + $accountsModule = Import-Module -Name $accountsName -MinimumVersion 2.7.5 -Scope Global -PassThru + } + } + } + + if(-not $accountsModule) { + Write-Error "`nThis module requires $accountsName version 2.7.5 or greater. For installation instructions, please see: https://learn.microsoft.com/powershell/azure/install-az-ps" -ErrorAction Stop + } elseif (($accountsModule.Version -lt [System.Version]'2.7.5') -and (-not $localAccounts)) { + Write-Error "`nThis module requires $accountsName version 2.7.5 or greater. An earlier version of Az.Accounts is imported in the current PowerShell session. If you are running test, please try to add the switch '-RegenerateSupportModule' when executing 'test-module.ps1'. 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.DataBoundary.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module]::Instance + + # Ask for the shared functionality table + $VTable = Register-AzModule + + # Tweaks the pipeline on module load + $instance.OnModuleLoad = $VTable.OnModuleLoad + + # Following two delegates are added for telemetry + $instance.GetTelemetryId = $VTable.GetTelemetryId + $instance.Telemetry = $VTable.Telemetry + + # Delegate to sanitize the output object + $instance.SanitizeOutput = $VTable.SanitizerHandler + + # Delegate to get the telemetry info + $instance.GetTelemetryInfo = $VTable.GetTelemetryInfo + + # 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.DataBoundary.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/Resources/DataBoundary.Autorest/README.md b/src/Resources/DataBoundary.Autorest/README.md new file mode 100644 index 000000000000..4753bce8aac6 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/README.md @@ -0,0 +1,62 @@ + +# Az.DataBoundary +This directory contains the PowerShell module for the DataBoundary service. + +--- +## 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 2.7.5 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.DataBoundary`, see [how-to.md](how-to.md). + + +### AutoRest Configuration +> see https://aka.ms/autorest + +```yaml +root-module-name: $(prefix).Resources +title: DataBoundary +module-version: 0.1.1 + +# pin the swagger version by using the commit id instead of branch name +commit: a6074b7654c388dec49c9969d0136cfeb03575c9 +tag: package-databoundaries-2024-08 +require: +# readme.azure.noprofile.md is the common configuration file + - $(this-folder)/../../readme.azure.noprofile.md + - $(repo)/specification/resources/resource-manager/readme.md +# If the swagger has not been put in the repo, you may uncomment the following line and refer to it locally +# - (this-folder)/relative-path-to-your-local-readme.md + +try-require: + - $(repo)/specification/resources/resource-manager/readme.powershell.md + +directive: +# Following are common directives which are normally required in all the RPs +# 1. Remove the unexpanded parameter set +# 2. For New-* cmdlets, ViaIdentity is not required +# Following two directives are v4 specific +- where: + variant: ^(Create|Update)(?!.*?(Expanded|JsonFilePath|JsonString)) + remove: true +- where: + variant: ^CreateViaIdentity.*$ + remove: true +- where: + verb: Update + remove: true + + ``` diff --git a/src/Resources/DataBoundary.Autorest/UX/Microsoft.Resources/dataBoundaries.json b/src/Resources/DataBoundary.Autorest/UX/Microsoft.Resources/dataBoundaries.json new file mode 100644 index 000000000000..e152dc78c0ed --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/UX/Microsoft.Resources/dataBoundaries.json @@ -0,0 +1,58 @@ +{ + "resourceType": "dataBoundaries", + "apiVersion": "2024-08-01", + "learnMore": { + "url": "https://learn.microsoft.com/powershell/module/az.resources" + }, + "commands": [ + { + "name": "Get-AzDataBoundaryScope", + "description": "Get data boundary at specified scope", + "path": "/{scope}/providers/Microsoft.Resources/dataBoundaries/{default}", + "help": { + "learnMore": { + "url": "https://learn.microsoft.com/powershell/module/az.resources/get-azdataboundaryscope" + }, + "parameterSets": [ + { + "parameters": [ + "-Scope " + ] + } + ] + }, + "examples": [ + { + "description": "Get data boundary at specified scope", + "parameters": [ + { + "name": "-Scope", + "value": "[Path.scope]" + } + ] + } + ] + }, + { + "name": "Get-AzDataBoundaryTenant", + "description": "Get data boundary of tenant.", + "path": "/providers/Microsoft.Resources/dataBoundaries/{default}", + "help": { + "learnMore": { + "url": "https://learn.microsoft.com/powershell/module/az.resources/get-azdataboundarytenant" + }, + "parameterSets": [ + { + "parameters": null + } + ] + }, + "examples": [ + { + "description": "Get data boundary of tenant.", + "parameters": null + } + ] + } + ] +} diff --git a/src/Resources/DataBoundary.Autorest/build-module.ps1 b/src/Resources/DataBoundary.Autorest/build-module.ps1 new file mode 100644 index 000000000000..94f0abd954af --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/build-module.ps1 @@ -0,0 +1,191 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Run, [switch]$Test, [switch]$Docs, [switch]$Pack, [switch]$Code, [switch]$Release, [switch]$Debugger, [switch]$NoDocs, [switch]$UX, [Switch]$DisableAfterBuildTasks) +$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 $NotIsolated -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 -NotIsolated + + 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($UX) { + . (Join-Path $PSScriptRoot 'generate-portal-ux.ps1') + if($LastExitCode -ne 0) { + # UX 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' + +$isAzure = [System.Convert]::ToBoolean('true') + +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.DataBoundary.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.DataBoundary.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.DataBoundary.psd1' +$guid = Get-ModuleGuid -Psd1Path $psd1 +$moduleName = 'Az.DataBoundary' +$examplesFolder = Join-Path $PSScriptRoot 'examples' +$null = New-Item -ItemType Directory -Force -Path $examplesFolder + +Write-Host -ForegroundColor Green 'Creating cmdlets for specified models...' +$modelCmdlets = @() +$modelCmdletFolder = Join-Path (Join-Path $PSScriptRoot './custom') 'autogen-model-cmdlets' +if (Test-Path $modelCmdletFolder) { + $null = Remove-Item -Force -Recurse -Path $modelCmdletFolder +} +if ($modelCmdlets.Count -gt 0) { + . (Join-Path $PSScriptRoot 'create-model-cmdlets.ps1') + CreateModelCmdlet($modelCmdlets) +} + +if($NoDocs) { + Write-Host -ForegroundColor Green 'Creating exports...' + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ExcludeDocs -ExamplesFolder $examplesFolder +} else { + Write-Host -ForegroundColor Green 'Creating exports and docs...' + $moduleDescription = 'Microsoft Azure PowerShell: DataBoundary 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 + $addComplexInterfaceInfo = !$isAzure + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ModuleDescription $moduleDescription -DocsFolder $docsFolder -ExamplesFolder $examplesFolder -ModuleGuid $guid -AddComplexInterfaceInfo:$addComplexInterfaceInfo +} + +Write-Host -ForegroundColor Green 'Creating format.ps1xml...' +$formatPs1xml = Join-Path $PSScriptRoot './Az.DataBoundary.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 + +if (Test-Path (Join-Path $PSScriptRoot 'generate-portal-ux.ps1')) +{ + Write-Host -ForegroundColor Green 'Creating ux metadata...' + . (Join-Path $PSScriptRoot 'generate-portal-ux.ps1') +} + +if (-not $DisableAfterBuildTasks){ + $afterBuildTasksPath = Join-Path $PSScriptRoot '' + $afterBuildTasksArgs = ConvertFrom-Json 'true' -AsHashtable + if(Test-Path -Path $afterBuildTasksPath -PathType leaf){ + Write-Host -ForegroundColor Green 'Running after build tasks...' + . $afterBuildTasksPath @afterBuildTasksArgs + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/check-dependencies.ps1 b/src/Resources/DataBoundary.Autorest/check-dependencies.ps1 new file mode 100644 index 000000000000..90ca9867ae40 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/check-dependencies.ps1 @@ -0,0 +1,65 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Accounts, [switch]$Pester, [switch]$Resources) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +function DownloadModule ([bool]$predicate, [string]$path, [string]$moduleName, [string]$versionMinimum, [string]$requiredVersion) { + 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) -or ($requiredVersion -and ($module | ForEach-Object { $_.Version } | Where-Object { $_ -eq [System.Version]$requiredVersion } | Measure-Object).Count -eq 0)) { + $null = New-Item -ItemType Directory -Force -Path $path + Write-Host -ForegroundColor Green "Installing local $moduleName module into '$path'..." + if ($requiredVersion) { + Find-Module -Name $moduleName -RequiredVersion $requiredVersion -Repository PSGallery | Save-Module -Path $path + }elseif($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 '2.7.5' +DownloadModule -predicate ($all -or $Pester) -path $localModulesPath -moduleName 'Pester' -requiredVersion '4.10.1' + +$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)) -or $RegenerateSupportModule.IsPresent)) { + Write-Host -ForegroundColor Green "Building local Resource module used for test..." + Set-Location $resourceDir + $null = autorest .\README.md --use:@autorest/powershell@3.0.414 --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/Resources/DataBoundary.Autorest/create-model-cmdlets.ps1 b/src/Resources/DataBoundary.Autorest/create-model-cmdlets.ps1 new file mode 100644 index 000000000000..ae781d9af625 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/create-model-cmdlets.ps1 @@ -0,0 +1,262 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +function CreateModelCmdlet { + + param([Hashtable[]]$Models) + + if ($Models.Count -eq 0) + { + return + } + + $ModelCsPath = Join-Path (Join-Path $PSScriptRoot 'generated\api') 'Models' + $OutputDir = Join-Path $PSScriptRoot 'custom\autogen-model-cmdlets' + $null = New-Item -ItemType Directory -Force -Path $OutputDir + if ('Az.Resources'.length -gt 0) { + $ModuleName = 'Az.Resources' + } else { + $ModuleName = 'Az.DataBoundary' + } + $CsFiles = Get-ChildItem -Path $ModelCsPath -Recurse -Filter *.cs + $Content = '' + $null = $CsFiles | ForEach-Object -Process { if ($_.Name.Split('.').count -eq 2 ) + { $Content += get-content $_.fullname -raw + } } + + $Tree = [Microsoft.CodeAnalysis.CSharp.SyntaxFactory]::ParseCompilationUnit($Content) + $Nodes = $Tree.ChildNodes().ChildNodes() + $classConstantMember = @{} + foreach ($Model in $Models) + { + $ModelName = $Model.modelName + $InterfaceNode = $Nodes | Where-Object { ($_.Keyword.value -eq 'interface') -and ($_.Identifier.value -eq "I$ModelName") } + $ClassNode = $Nodes | Where-Object { ($_.Keyword.value -eq 'class') -and ($_.Identifier.value -eq "$ModelName") } + $classConstantMember = @() + foreach ($class in $ClassNode) { + foreach ($member in $class.Members) { + $isConstant = $false + foreach ($attr in $member.AttributeLists) { + $memberName = $attr.Attributes.Name.ToString() + if ($memberName.EndsWith('.Constant')) { + $isConstant = $true + break + } + } + if (($member.Modifiers.ToString() -eq 'public') -and $isConstant) { + $classConstantMember += $member.Identifier.Value + } + } + } + if ($InterfaceNode.count -eq 0) { + continue + } + # through a queue, we iterate all the parent models. + $Queue = @($InterfaceNode) + $visited = @("I$ModelName") + $AllInterfaceNodes = @() + while ($Queue.count -ne 0) + { + $AllInterfaceNodes += $Queue[0] + # Baselist contains the direct parent models. + foreach ($parent in $Queue[0].BaseList.Types) + { + if (($parent.Type.Right.Identifier.Value -ne 'IJsonSerializable') -and (-not $visited.Contains($parent.Type.Right.Identifier.Value))) + { + $Queue = [Array]$Queue + ($Nodes | Where-Object { ($_.Keyword.value -eq 'interface') -and ($_.Identifier.value -eq $parent.Type.Right.Identifier.Value) }) + $visited = [Array]$visited + $parent.Type.Right.Identifier.Value + } + } + $first, $Queue = $Queue + } + + $Namespace = $InterfaceNode.Parent.Name + $ObjectType = $ModelName + $ObjectTypeWithNamespace = "${Namespace}.${ObjectType}" + # remove duplicated module name + if ($ObjectType.StartsWith('DataBoundary')) { + $ModulePrefix = '' + } else { + $ModulePrefix = 'DataBoundary' + } + $OutputPath = Join-Path -ChildPath "New-Az${ModulePrefix}${ObjectType}Object.ps1" -Path $OutputDir + + $ParameterDefineScriptList = New-Object System.Collections.Generic.List[string] + $ParameterAssignScriptList = New-Object System.Collections.Generic.List[string] + foreach ($Node in $AllInterfaceNodes) + { + foreach ($Member in $Node.Members) + { + if ($classConstantMember.Contains($Member.Identifier.Value)) { + # skip constant member + continue + } + $Arguments = $Member.AttributeLists.Attributes.ArgumentList.Arguments + $Required = $false + $Description = "" + $Readonly = $False + $mutability = @{Read = $true; Create = $true; Update = $true} + foreach ($Argument in $Arguments) + { + if ($Argument.NameEquals.Name.Identifier.Value -eq "Required") + { + $Required = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Description") + { + $Description = $Argument.Expression.Token.Value.Trim('.').replace('"', '`"') + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Readonly") + { + $Readonly = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Read") + { + $mutability.Read = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Create") + { + $mutability.Create = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Update") + { + $mutability.Update = $Argument.Expression.Token.Value + } + } + if ($Readonly) + { + continue + } + $Identifier = $Member.Identifier.Value + $Type = $Member.Type.ToString().replace('?', '').Split("::")[-1] + $Type = $Member.Type.ToString().replace('?', '').Split("::")[-1] + if ($Type.StartsWith("System.Collections.Generic.List")) + { + # if the type is a list, we need to convert it to array + $matched = $Type -match '\<(?.+)\>$' + if ($matched) + { + $Type = $matches.Name + '[]'; + } + } + $ParameterDefinePropertyList = New-Object System.Collections.Generic.List[string] + if ($Required -and $mutability.Create -and $mutability.Update) + { + $ParameterDefinePropertyList.Add("Mandatory") + } + if ($Description -ne "") + { + $ParameterDefinePropertyList.Add("HelpMessage=`"${Description}.`"") + } + $ParameterDefineProperty = [System.String]::Join(", ", $ParameterDefinePropertyList) + # check whether completer is needed + $completer = ''; + if(IsEnumType($Member)){ + $completer += GetCompleter($Member) + } + $ParameterDefineScript = " + [Parameter($ParameterDefineProperty)]${completer} + [${Type}] + `$${Identifier}" + $ParameterDefineScriptList.Add($ParameterDefineScript) + $ParameterAssignScriptList.Add(" + if (`$PSBoundParameters.ContainsKey('${Identifier}')) { + `$Object.${Identifier} = `$${Identifier} + }") + } + } + $ParameterDefineScript = $ParameterDefineScriptList | Join-String -Separator "," + $ParameterAssignScript = $ParameterAssignScriptList | Join-String -Separator "" + + $cmdletName = "New-Az${ModulePrefix}${ObjectType}Object" + if ('' -ne $Model.cmdletName) { + $cmdletName = $Model.cmdletName + } + $OutputPath = Join-Path -ChildPath "${cmdletName}.ps1" -Path $OutputDir + $cmdletNameInLowerCase = $cmdletName.ToLower() + $Script = " +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Create an in-memory object for ${ObjectType}. +.Description +Create an in-memory object for ${ObjectType}. + +.Outputs +${ObjectTypeWithNamespace} +.Link +https://learn.microsoft.com/powershell/module/${ModuleName}/${cmdletNameInLowerCase} +#> +function ${cmdletName} { + [OutputType('${ObjectTypeWithNamespace}')] + [CmdletBinding(PositionalBinding=`$false)] + Param( +${ParameterDefineScript} + ) + + process { + `$Object = [${ObjectTypeWithNamespace}]::New() +${ParameterAssignScript} + return `$Object + } +} +" + Set-Content -Path $OutputPath -Value $Script + } +} + +function IsEnumType { + param ( + [Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax]$property + ) + $isEnum = $false + foreach ($attr in $property.AttributeLists) { + $attributeName = $attr.Attributes.Name.ToString() + if ($attributeName.Contains('ArgumentCompleter')) { + $isEnum = $true + break + } + } + return $isEnum; +} + +function GetCompleter { + param ( + [Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax]$property + ) + foreach ($attr in $property.AttributeLists) { + $attributeName = $attr.Attributes.Name.ToString() + if ($attributeName.Contains('ArgumentCompleter')) { + $attributeName = $attributeName.Split("::")[-1] + $possibleValues = [System.String]::Join(", ", $attr.Attributes.ArgumentList.Arguments) + $completer += "`n [${attributeName}(${possibleValues})]" + return $completer + } + } +} diff --git a/src/Resources/DataBoundary.Autorest/custom/Az.DataBoundary.custom.psm1 b/src/Resources/DataBoundary.Autorest/custom/Az.DataBoundary.custom.psm1 new file mode 100644 index 000000000000..d37c02495b09 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/custom/Az.DataBoundary.custom.psm1 @@ -0,0 +1,17 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.DataBoundary.private.dll') + + # Load the internal module + $internalModulePath = Join-Path $PSScriptRoot '..\internal\Az.DataBoundary.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/Resources/DataBoundary.Autorest/custom/README.md b/src/Resources/DataBoundary.Autorest/custom/README.md new file mode 100644 index 000000000000..7543a2aef761 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/custom/README.md @@ -0,0 +1,41 @@ +# Custom +This directory contains custom implementation for non-generated cmdlets for the `Az.DataBoundary` 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.DataBoundary.custom.psm1`. This file should not be modified. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: yes + +## Details +For `Az.DataBoundary` 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.DataBoundary.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.DataBoundary.custom.psm1`. Then, during the build process, this module is loaded and processed in the same manner as the C# cmdlets. The fundamental 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.DataBoundary`. 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.DataBoundary.DescriptionAttribute` + - Used in C# cmdlets to provide a high-level description of the cmdlet. This is propagated to reference documentation via [help comments](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_comment_based_help) in the exported scripts. +- `Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.DoNotExportAttribute` + - Used in C# and script cmdlets to suppress creating an exported cmdlet at build-time. These cmdlets will *not be exposed* by `Az.DataBoundary`. +- `Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.InternalExportAttribute` + - Used in C# cmdlets to route exported cmdlets to the `..\internal`, which are *not exposed* by `Az.DataBoundary`. For more information, see [README.md](..\internal/README.md) in the `..\internal` folder. +- `Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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/Resources/DataBoundary.Autorest/examples/Get-AzDataBoundaryScope.md b/src/Resources/DataBoundary.Autorest/examples/Get-AzDataBoundaryScope.md new file mode 100644 index 000000000000..a4cb15e4aa35 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/examples/Get-AzDataBoundaryScope.md @@ -0,0 +1,30 @@ +### Example 1: Get Subscription Scoped Data Boundary + +```powershell +$scope = "/subscriptions/11111111-1111-1111-1111-111111111111" +Get-AzDataBoundaryScope -Scope $scope +``` + +```output +Name Id Properties +-------- ---- ------------ +00000000-0000-0000-0000-000000000000 /providers/Microsoft.Resources/dataBoundaries/00000000-0000-0000-0000-000000000000 dataBoundary: EU, provisioningState: Created +``` + +Gets the dataBoundary at the subscription scope. + +### Example 2: Get Resource Group Scoped Data Boundary + +```powershell +$scope = "/subscriptions/11111111-1111-1111-1111-111111111111/resourcegroups/my-resource-group" +Get-AzDataBoundaryScope -Scope $scope +``` + +```output +Name Id Properties +-------- ---- ------------ +00000000-0000-0000-0000-000000000000 /providers/Microsoft.Resources/dataBoundaries/00000000-0000-0000-0000-000000000000 dataBoundary: EU, provisioningState: Created +``` + +Gets the dataBoundary at the resource group scope. + diff --git a/src/Resources/DataBoundary.Autorest/examples/Get-AzDataBoundaryTenant.md b/src/Resources/DataBoundary.Autorest/examples/Get-AzDataBoundaryTenant.md new file mode 100644 index 000000000000..0c0cb5c9d980 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/examples/Get-AzDataBoundaryTenant.md @@ -0,0 +1,13 @@ +### Example 1: Get Tenant Level Data Boundary + +```powershell +Get-AzDataBoundaryTenant +``` + +```output +Name Id Properties +-------- ---- ------------ +00000000-0000-0000-0000-000000000000 /providers/Microsoft.Resources/dataBoundaries/00000000-0000-0000-0000-000000000000 dataBoundary: EU, provisioningState: Created +``` + +Gets the dataBoundary at the tenant level. \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/examples/Set-AzDataBoundary.md b/src/Resources/DataBoundary.Autorest/examples/Set-AzDataBoundary.md new file mode 100644 index 000000000000..c1157c07c95a --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/examples/Set-AzDataBoundary.md @@ -0,0 +1,14 @@ +### Example 1: Set Tenant Level Data Boundary + +```powershell +$dataBoundary = "EU" +Set-AzDataBoundary -DataBoundary $dataBoundary +``` + +```output +Name Id Properties +-------- ---- ------------ +00000000-0000-0000-0000-000000000000 /providers/Microsoft.Resources/dataBoundaries/00000000-0000-0000-0000-000000000000 dataBoundary: EU, provisioningState: Created +``` + +Sets the dataBoundary at the tenant level. diff --git a/src/Resources/DataBoundary.Autorest/export-surface.ps1 b/src/Resources/DataBoundary.Autorest/export-surface.ps1 new file mode 100644 index 000000000000..7aa769f8ba61 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/export-surface.ps1 @@ -0,0 +1,41 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$IncludeGeneralParameters, [switch]$UseExpandedFormat) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.DataBoundary.private.dll' +if(-not (Test-Path $dll)) { + Write-Error "Unable to find output assembly in '$binFolder'." +} +$null = Import-Module -Name $dll + +$moduleName = 'Az.DataBoundary' +$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/Resources/DataBoundary.Autorest/exports/Get-AzDataBoundaryScope.ps1 b/src/Resources/DataBoundary.Autorest/exports/Get-AzDataBoundaryScope.ps1 new file mode 100644 index 000000000000..4f8512143347 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/exports/Get-AzDataBoundaryScope.ps1 @@ -0,0 +1,169 @@ + +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Get data boundary at specified scope +.Description +Get data boundary at specified scope +.Example +$scope = "/subscriptions/11111111-1111-1111-1111-111111111111" +Get-AzDataBoundaryScope -Scope $scope +.Example +$scope = "/subscriptions/11111111-1111-1111-1111-111111111111/resourcegroups/my-resource-group" +Get-AzDataBoundaryScope -Scope $scope + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition +.Link +https://learn.microsoft.com/powershell/module/az.resources/get-azdataboundaryscope +#> +function Get-AzDataBoundaryScope { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition])] +[CmdletBinding(DefaultParameterSetName='Get', PositionalBinding=$false)] +param( + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Path')] + [System.String] + # The scope at which the operation is performed. + ${Scope}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Azure')] + [System.Management.Automation.PSObject] + # The DefaultProfile parameter is not functional. + # Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 + + if ($null -eq [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion) { + [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion = $PSVersionTable.PSVersion.ToString() + } + $preTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId + if ($preTelemetryId -eq '') { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId =(New-Guid).ToString() + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.module]::Instance.Telemetry.Invoke('Create', $MyInvocation, $parameterSet, $PSCmdlet) + } else { + $internalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets + if ($internalCalledCmdlets -eq '') { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $MyInvocation.MyCommand.Name + } else { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets += ',' + $MyInvocation.MyCommand.Name + } + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = 'internal' + } + + $mapping = @{ + Get = 'Az.DataBoundary.private\Get-AzDataBoundaryScope_Get'; + } + $cmdInfo = Get-Command -Name $mapping[$parameterSet] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) + if ($null -ne $MyInvocation.MyCommand -and [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets -notcontains $MyInvocation.MyCommand.Name -and [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ContainsPreviewAttribute($cmdInfo, $MyInvocation)){ + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) + [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets.Enqueue($MyInvocation.MyCommand.Name) + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } + + finally { + $backupTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId + $backupInternalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + } + +} +end { + try { + $steppablePipeline.End() + + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $backupTelemetryId + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $backupInternalCalledCmdlets + if ($preTelemetryId -eq '') { + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.module]::Instance.Telemetry.Invoke('Send', $MyInvocation, $parameterSet, $PSCmdlet) + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + } + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $preTelemetryId + + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } +} +} diff --git a/src/Resources/DataBoundary.Autorest/exports/Get-AzDataBoundaryTenant.ps1 b/src/Resources/DataBoundary.Autorest/exports/Get-AzDataBoundaryTenant.ps1 new file mode 100644 index 000000000000..cf49a91154a1 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/exports/Get-AzDataBoundaryTenant.ps1 @@ -0,0 +1,159 @@ + +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Get data boundary of tenant. +.Description +Get data boundary of tenant. +.Example +Get-AzDataBoundaryTenant + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition +.Link +https://learn.microsoft.com/powershell/module/az.resources/get-azdataboundarytenant +#> +function Get-AzDataBoundaryTenant { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition])] +[CmdletBinding(DefaultParameterSetName='Get', PositionalBinding=$false)] +param( + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Azure')] + [System.Management.Automation.PSObject] + # The DefaultProfile parameter is not functional. + # Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 + + if ($null -eq [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion) { + [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion = $PSVersionTable.PSVersion.ToString() + } + $preTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId + if ($preTelemetryId -eq '') { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId =(New-Guid).ToString() + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.module]::Instance.Telemetry.Invoke('Create', $MyInvocation, $parameterSet, $PSCmdlet) + } else { + $internalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets + if ($internalCalledCmdlets -eq '') { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $MyInvocation.MyCommand.Name + } else { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets += ',' + $MyInvocation.MyCommand.Name + } + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = 'internal' + } + + $mapping = @{ + Get = 'Az.DataBoundary.private\Get-AzDataBoundaryTenant_Get'; + } + $cmdInfo = Get-Command -Name $mapping[$parameterSet] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) + if ($null -ne $MyInvocation.MyCommand -and [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets -notcontains $MyInvocation.MyCommand.Name -and [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ContainsPreviewAttribute($cmdInfo, $MyInvocation)){ + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) + [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets.Enqueue($MyInvocation.MyCommand.Name) + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } + + finally { + $backupTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId + $backupInternalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + } + +} +end { + try { + $steppablePipeline.End() + + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $backupTelemetryId + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $backupInternalCalledCmdlets + if ($preTelemetryId -eq '') { + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.module]::Instance.Telemetry.Invoke('Send', $MyInvocation, $parameterSet, $PSCmdlet) + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + } + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $preTelemetryId + + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } +} +} diff --git a/src/Resources/DataBoundary.Autorest/exports/ProxyCmdletDefinitions.ps1 b/src/Resources/DataBoundary.Autorest/exports/ProxyCmdletDefinitions.ps1 new file mode 100644 index 000000000000..1ee4365b1387 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/exports/ProxyCmdletDefinitions.ps1 @@ -0,0 +1,495 @@ + +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Get data boundary at specified scope +.Description +Get data boundary at specified scope +.Example +$scope = "/subscriptions/11111111-1111-1111-1111-111111111111" +Get-AzDataBoundaryScope -Scope $scope +.Example +$scope = "/subscriptions/11111111-1111-1111-1111-111111111111/resourcegroups/my-resource-group" +Get-AzDataBoundaryScope -Scope $scope + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition +.Link +https://learn.microsoft.com/powershell/module/az.resources/get-azdataboundaryscope +#> +function Get-AzDataBoundaryScope { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition])] +[CmdletBinding(DefaultParameterSetName='Get', PositionalBinding=$false)] +param( + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Path')] + [System.String] + # The scope at which the operation is performed. + ${Scope}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Azure')] + [System.Management.Automation.PSObject] + # The DefaultProfile parameter is not functional. + # Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 + + if ($null -eq [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion) { + [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion = $PSVersionTable.PSVersion.ToString() + } + $preTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId + if ($preTelemetryId -eq '') { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId =(New-Guid).ToString() + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.module]::Instance.Telemetry.Invoke('Create', $MyInvocation, $parameterSet, $PSCmdlet) + } else { + $internalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets + if ($internalCalledCmdlets -eq '') { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $MyInvocation.MyCommand.Name + } else { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets += ',' + $MyInvocation.MyCommand.Name + } + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = 'internal' + } + + $mapping = @{ + Get = 'Az.DataBoundary.private\Get-AzDataBoundaryScope_Get'; + } + $cmdInfo = Get-Command -Name $mapping[$parameterSet] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) + if ($null -ne $MyInvocation.MyCommand -and [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets -notcontains $MyInvocation.MyCommand.Name -and [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ContainsPreviewAttribute($cmdInfo, $MyInvocation)){ + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) + [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets.Enqueue($MyInvocation.MyCommand.Name) + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } + + finally { + $backupTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId + $backupInternalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + } + +} +end { + try { + $steppablePipeline.End() + + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $backupTelemetryId + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $backupInternalCalledCmdlets + if ($preTelemetryId -eq '') { + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.module]::Instance.Telemetry.Invoke('Send', $MyInvocation, $parameterSet, $PSCmdlet) + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + } + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $preTelemetryId + + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } +} +} + +<# +.Synopsis +Get data boundary of tenant. +.Description +Get data boundary of tenant. +.Example +Get-AzDataBoundaryTenant + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition +.Link +https://learn.microsoft.com/powershell/module/az.resources/get-azdataboundarytenant +#> +function Get-AzDataBoundaryTenant { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition])] +[CmdletBinding(DefaultParameterSetName='Get', PositionalBinding=$false)] +param( + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Azure')] + [System.Management.Automation.PSObject] + # The DefaultProfile parameter is not functional. + # Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 + + if ($null -eq [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion) { + [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion = $PSVersionTable.PSVersion.ToString() + } + $preTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId + if ($preTelemetryId -eq '') { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId =(New-Guid).ToString() + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.module]::Instance.Telemetry.Invoke('Create', $MyInvocation, $parameterSet, $PSCmdlet) + } else { + $internalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets + if ($internalCalledCmdlets -eq '') { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $MyInvocation.MyCommand.Name + } else { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets += ',' + $MyInvocation.MyCommand.Name + } + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = 'internal' + } + + $mapping = @{ + Get = 'Az.DataBoundary.private\Get-AzDataBoundaryTenant_Get'; + } + $cmdInfo = Get-Command -Name $mapping[$parameterSet] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) + if ($null -ne $MyInvocation.MyCommand -and [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets -notcontains $MyInvocation.MyCommand.Name -and [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ContainsPreviewAttribute($cmdInfo, $MyInvocation)){ + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) + [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets.Enqueue($MyInvocation.MyCommand.Name) + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } + + finally { + $backupTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId + $backupInternalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + } + +} +end { + try { + $steppablePipeline.End() + + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $backupTelemetryId + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $backupInternalCalledCmdlets + if ($preTelemetryId -eq '') { + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.module]::Instance.Telemetry.Invoke('Send', $MyInvocation, $parameterSet, $PSCmdlet) + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + } + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $preTelemetryId + + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } +} +} + +<# +.Synopsis +Opt-in tenant to data boundary. +.Description +Opt-in tenant to data boundary. +.Example +$dataBoundary = "EU" +Set-AzDataBoundary -DataBoundary $dataBoundary + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition +.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. + +DATABOUNDARYDEFINITION : A data boundary definition. + [DataBoundary ]: The data boundary definition. +.Link +https://learn.microsoft.com/powershell/module/az.resources/set-azdataboundary +#> +function Set-AzDataBoundary { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition])] +[CmdletBinding(DefaultParameterSetName='PutExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Put', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition] + # A data boundary definition. + ${DataBoundaryDefinition}, + + [Parameter(ParameterSetName='PutExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("NotDefined", "Global", "EU")] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Body')] + [System.String] + # The data boundary definition. + ${DataBoundary}, + + [Parameter(ParameterSetName='PutViaJsonFilePath', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Body')] + [System.String] + # Path of Json file supplied to the Put operation + ${JsonFilePath}, + + [Parameter(ParameterSetName='PutViaJsonString', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Body')] + [System.String] + # Json string supplied to the Put operation + ${JsonString}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Azure')] + [System.Management.Automation.PSObject] + # The DefaultProfile parameter is not functional. + # Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 + + if ($null -eq [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion) { + [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion = $PSVersionTable.PSVersion.ToString() + } + $preTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId + if ($preTelemetryId -eq '') { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId =(New-Guid).ToString() + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.module]::Instance.Telemetry.Invoke('Create', $MyInvocation, $parameterSet, $PSCmdlet) + } else { + $internalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets + if ($internalCalledCmdlets -eq '') { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $MyInvocation.MyCommand.Name + } else { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets += ',' + $MyInvocation.MyCommand.Name + } + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = 'internal' + } + + $mapping = @{ + Put = 'Az.DataBoundary.private\Set-AzDataBoundary_Put'; + PutExpanded = 'Az.DataBoundary.private\Set-AzDataBoundary_PutExpanded'; + PutViaJsonFilePath = 'Az.DataBoundary.private\Set-AzDataBoundary_PutViaJsonFilePath'; + PutViaJsonString = 'Az.DataBoundary.private\Set-AzDataBoundary_PutViaJsonString'; + } + $cmdInfo = Get-Command -Name $mapping[$parameterSet] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) + if ($null -ne $MyInvocation.MyCommand -and [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets -notcontains $MyInvocation.MyCommand.Name -and [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ContainsPreviewAttribute($cmdInfo, $MyInvocation)){ + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) + [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets.Enqueue($MyInvocation.MyCommand.Name) + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } + + finally { + $backupTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId + $backupInternalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + } + +} +end { + try { + $steppablePipeline.End() + + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $backupTelemetryId + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $backupInternalCalledCmdlets + if ($preTelemetryId -eq '') { + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.module]::Instance.Telemetry.Invoke('Send', $MyInvocation, $parameterSet, $PSCmdlet) + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + } + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $preTelemetryId + + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } +} +} diff --git a/src/Resources/DataBoundary.Autorest/exports/README.md b/src/Resources/DataBoundary.Autorest/exports/README.md new file mode 100644 index 000000000000..f13ec25fd7bd --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/exports/README.md @@ -0,0 +1,20 @@ +# Exports +This directory contains the cmdlets *exported by* `Az.DataBoundary`. No other cmdlets in this repository are directly exported. What that means is the `Az.DataBoundary` module will run [Export-ModuleMember](https://learn.microsoft.com/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.DataBoundary.private.dll`) and from the `..\custom\Az.DataBoundary.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.DataBoundary.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/Resources/DataBoundary.Autorest/exports/Set-AzDataBoundary.ps1 b/src/Resources/DataBoundary.Autorest/exports/Set-AzDataBoundary.ps1 new file mode 100644 index 000000000000..f00a9d693ff8 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/exports/Set-AzDataBoundary.ps1 @@ -0,0 +1,197 @@ + +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Opt-in tenant to data boundary. +.Description +Opt-in tenant to data boundary. +.Example +$dataBoundary = "EU" +Set-AzDataBoundary -DataBoundary $dataBoundary + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition +.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. + +DATABOUNDARYDEFINITION : A data boundary definition. + [DataBoundary ]: The data boundary definition. +.Link +https://learn.microsoft.com/powershell/module/az.resources/set-azdataboundary +#> +function Set-AzDataBoundary { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition])] +[CmdletBinding(DefaultParameterSetName='PutExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Put', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition] + # A data boundary definition. + ${DataBoundaryDefinition}, + + [Parameter(ParameterSetName='PutExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("NotDefined", "Global", "EU")] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Body')] + [System.String] + # The data boundary definition. + ${DataBoundary}, + + [Parameter(ParameterSetName='PutViaJsonFilePath', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Body')] + [System.String] + # Path of Json file supplied to the Put operation + ${JsonFilePath}, + + [Parameter(ParameterSetName='PutViaJsonString', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Body')] + [System.String] + # Json string supplied to the Put operation + ${JsonString}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Azure')] + [System.Management.Automation.PSObject] + # The DefaultProfile parameter is not functional. + # Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 + + if ($null -eq [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion) { + [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion = $PSVersionTable.PSVersion.ToString() + } + $preTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId + if ($preTelemetryId -eq '') { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId =(New-Guid).ToString() + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.module]::Instance.Telemetry.Invoke('Create', $MyInvocation, $parameterSet, $PSCmdlet) + } else { + $internalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets + if ($internalCalledCmdlets -eq '') { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $MyInvocation.MyCommand.Name + } else { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets += ',' + $MyInvocation.MyCommand.Name + } + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = 'internal' + } + + $mapping = @{ + Put = 'Az.DataBoundary.private\Set-AzDataBoundary_Put'; + PutExpanded = 'Az.DataBoundary.private\Set-AzDataBoundary_PutExpanded'; + PutViaJsonFilePath = 'Az.DataBoundary.private\Set-AzDataBoundary_PutViaJsonFilePath'; + PutViaJsonString = 'Az.DataBoundary.private\Set-AzDataBoundary_PutViaJsonString'; + } + $cmdInfo = Get-Command -Name $mapping[$parameterSet] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) + if ($null -ne $MyInvocation.MyCommand -and [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets -notcontains $MyInvocation.MyCommand.Name -and [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ContainsPreviewAttribute($cmdInfo, $MyInvocation)){ + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) + [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets.Enqueue($MyInvocation.MyCommand.Name) + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } + + finally { + $backupTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId + $backupInternalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + } + +} +end { + try { + $steppablePipeline.End() + + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $backupTelemetryId + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $backupInternalCalledCmdlets + if ($preTelemetryId -eq '') { + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.module]::Instance.Telemetry.Invoke('Send', $MyInvocation, $parameterSet, $PSCmdlet) + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + } + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $preTelemetryId + + } catch { + [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() + throw + } +} +} diff --git a/src/Resources/DataBoundary.Autorest/generate-help.ps1 b/src/Resources/DataBoundary.Autorest/generate-help.ps1 new file mode 100644 index 000000000000..3f8b1734ed9d --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generate-help.ps1 @@ -0,0 +1,74 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + 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.DataBoundary.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.DataBoundary.private.dll') +$instance = [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 + $addComplexInterfaceInfo = ![System.Convert]::ToBoolean('true') + Export-HelpMarkdown -ModuleInfo $moduleInfo -FunctionInfo $cmdletFunctionInfo -HelpInfo $cmdletHelpInfo -DocsFolder $docsPath -ExamplesFolder $examplesPath -AddComplexInterfaceInfo:$addComplexInterfaceInfo + Write-Host -ForegroundColor Green "Created documentation in '$docsPath'" +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generate-portal-ux.ps1 b/src/Resources/DataBoundary.Autorest/generate-portal-ux.ps1 new file mode 100644 index 000000000000..ee5f0e95f809 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generate-portal-ux.ps1 @@ -0,0 +1,374 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# +# This Script will create a folder dedicated to Azure-specific content and includes metadata files essential for enhancing the user experience (UX) within the Azure portal. +# These files are utilized by the Azure portal to effectively present the usage of cmdlets related to specific resources on portal pages. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$moduleName = 'Az.DataBoundary' +$rootModuleName = 'Az.Resources' +if ($rootModuleName -eq "") +{ + $rootModuleName = $moduleName +} +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot "./$moduleName.psd1") +$modulePath = $modulePsd1.FullName + +# Load DLL to use build-time cmdlets +Import-Module -Name $modulePath +Import-Module -Name (Join-Path $PSScriptRoot "./bin/$moduleName.private.dll") +$instance = [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module]::Instance +# Module info is shared per profile +$moduleInfo = Get-Module -Name $moduleName +$parameterSetsInfo = Get-Module -Name "$moduleName.private" + +function Test-FunctionSupported() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [string] + $FunctionName + ) + + If (-not $FunctionName.Contains("_")) { + return $false + } + + $cmdletName, $parameterSetName = $FunctionName.Split("_") + If ($parameterSetName.Contains("List") -or $parameterSetName.Contains("ViaIdentity") -or $parameterSetName.Contains("ViaJson")) { + return $false + } + If ($cmdletName.StartsWith("New") -or $cmdletName.StartsWith("Set") -or $cmdletName.StartsWith("Update")) { + return $false + } + + $parameterSetInfo = $parameterSetsInfo.ExportedCmdlets[$FunctionName] + foreach ($parameterInfo in $parameterSetInfo.Parameters.Values) + { + $category = (Get-ParameterAttribute -ParameterInfo $parameterInfo -AttributeName "CategoryAttribute").Categories + $invalideCategory = @('Query', 'Body') + if ($invalideCategory -contains $category) + { + return $false + } + } + + $customFiles = Get-ChildItem -Path custom -Filter "$cmdletName.*" + if ($customFiles.Length -ne 0) + { + Write-Host -ForegroundColor Yellow "There are come custom files for $cmdletName, skip generate UX data for it." + return $false + } + + return $true +} + +function Get-MappedCmdletFromFunctionName() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [string] + $FunctionName + ) + + $cmdletName, $parameterSetName = $FunctionName.Split("_") + + return $cmdletName +} + +function Get-ParameterAttribute() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.ParameterMetadata] + $ParameterInfo, + [Parameter()] + [String] + $AttributeName + ) + return $ParameterInfo.Attributes | Where-Object { $_.TypeId.Name -eq $AttributeName } +} + +function Get-CmdletAttribute() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $CmdletInfo, + [Parameter()] + [String] + $AttributeName + ) + + return $CmdletInfo.ImplementingType.GetTypeInfo().GetCustomAttributes([System.object], $true) | Where-Object { $_.TypeId.Name -eq $AttributeName } +} + +function Get-CmdletDescription() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [String] + $CmdletName + ) + $helpInfo = Get-Help $CmdletName -Full + + $description = $helpInfo.Description.Text + if ($null -eq $description) + { + return "" + } + return $description +} + +# Test whether the parameter is from swagger http path +function Test-ParameterFromSwagger() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.ParameterMetadata] + $ParameterInfo + ) + $category = (Get-ParameterAttribute -ParameterInfo $ParameterInfo -AttributeName "CategoryAttribute").Categories + $doNotExport = Get-ParameterAttribute -ParameterInfo $ParameterInfo -AttributeName "DoNotExportAttribute" + if ($null -ne $doNotExport) + { + return $false + } + + $valideCategory = @('Path') + if ($valideCategory -contains $category) + { + return $true + } + return $false +} + +function New-ExampleForParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $parameters = $ParameterSetInfo.Parameters.Values | Where-Object { Test-ParameterFromSwagger $_ } + $result = @() + foreach ($parameter in $parameters) + { + $category = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "CategoryAttribute").Categories + $sourceName = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "InfoAttribute").SerializedName + $name = $parameter.Name + $result += [ordered]@{ + name = "-$Name" + value = "[$category.$sourceName]" + } + } + + return $result +} + +function New-ParameterArrayInParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $parameters = $ParameterSetInfo.Parameters.Values | Where-Object { Test-ParameterFromSwagger $_ } + $result = @() + foreach ($parameter in $parameters) + { + $isMandatory = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "ParameterAttribute").Mandatory + $parameterName = $parameter.Name + $parameterType = $parameter.ParameterType.ToString().Split('.')[1] + if ($parameter.SwitchParameter) + { + $parameterSignature = "-$parameterName" + } + else + { + $parameterSignature = "-$parameterName <$parameterType>" + } + if ($parameterName -eq "SubscriptionId") + { + $isMandatory = $false + } + if (-not $isMandatory) + { + $parameterSignature = "[$parameterSignature]" + } + $result += $parameterSignature + } + + return $result +} + +function New-MetadataForParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $httpAttribute = Get-CmdletAttribute -CmdletInfo $ParameterSetInfo -AttributeName "HttpPathAttribute" + $httpPath = $httpAttribute.Path + $apiVersion = $httpAttribute.ApiVersion + $provider = [System.Text.RegularExpressions.Regex]::New("/providers/([\w+\.]+)/").Match($httpPath).Groups[1].Value + $resourcePath = "/" + $httpPath.Split("$provider/")[1] + $resourceType = [System.Text.RegularExpressions.Regex]::New("/([\w]+)/\{\w+\}").Matches($resourcePath) | ForEach-Object {$_.groups[1].Value} | Join-String -Separator "/" + $cmdletName = Get-MappedCmdletFromFunctionName $ParameterSetInfo.Name + $description = (Get-CmdletAttribute -CmdletInfo $ParameterSetInfo -AttributeName "DescriptionAttribute").Description + [object[]]$example = New-ExampleForParameterSet $ParameterSetInfo + [string[]]$signature = New-ParameterArrayInParameterSet $ParameterSetInfo + + return @{ + Path = $httpPath + Provider = $provider + ResourceType = $resourceType + ApiVersion = $apiVersion + CmdletName = $cmdletName + Description = $description + Example = $example + Signature = @{ + parameters = $signature + } + } +} + +function Merge-WithExistCmdletMetadata() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Collections.Specialized.OrderedDictionary] + $ExistedCmdletInfo, + [Parameter()] + [Hashtable] + $ParameterSetMetadata + ) + $ExistedCmdletInfo.help.parameterSets += $ParameterSetMetadata.Signature + $ExistedCmdletInfo.examples += [ordered]@{ + description = $ParameterSetMetadata.Description + parameters = $ParameterSetMetadata.Example + } + + return $ExistedCmdletInfo +} + +function New-MetadataForCmdlet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [Hashtable] + $ParameterSetMetadata + ) + $cmdletName = $ParameterSetMetadata.CmdletName + $description = Get-CmdletDescription $cmdletName + $result = [ordered]@{ + name = $cmdletName + description = $description + path = $ParameterSetMetadata.Path + help = [ordered]@{ + learnMore = [ordered]@{ + url = "https://learn.microsoft.com/powershell/module/$rootModuleName/$cmdletName".ToLower() + } + parameterSets = @() + } + examples = @() + } + $result = Merge-WithExistCmdletMetadata -ExistedCmdletInfo $result -ParameterSetMetadata $ParameterSetMetadata + return $result +} + +$parameterSets = $parameterSetsInfo.ExportedCmdlets.Keys | Where-Object { Test-FunctionSupported($_) } +$resourceTypes = @{} +foreach ($parameterSetName in $parameterSets) +{ + $cmdletInfo = $parameterSetsInfo.ExportedCommands[$parameterSetName] + $parameterSetMetadata = New-MetadataForParameterSet -ParameterSetInfo $cmdletInfo + $cmdletName = $parameterSetMetadata.CmdletName + if (-not ($moduleInfo.ExportedCommands.ContainsKey($cmdletName))) + { + continue + } + if ($resourceTypes.ContainsKey($parameterSetMetadata.ResourceType)) + { + $ExistedCmdletInfo = $resourceTypes[$parameterSetMetadata.ResourceType].commands | Where-Object { $_.name -eq $cmdletName } + if ($ExistedCmdletInfo) + { + $ExistedCmdletInfo = Merge-WithExistCmdletMetadata -ExistedCmdletInfo $ExistedCmdletInfo -ParameterSetMetadata $parameterSetMetadata + } + else + { + $cmdletInfo = New-MetadataForCmdlet -ParameterSetMetadata $parameterSetMetadata + $resourceTypes[$parameterSetMetadata.ResourceType].commands += $cmdletInfo + } + } + else + { + $cmdletInfo = New-MetadataForCmdlet -ParameterSetMetadata $parameterSetMetadata + $resourceTypes[$parameterSetMetadata.ResourceType] = [ordered]@{ + resourceType = $parameterSetMetadata.ResourceType + apiVersion = $parameterSetMetadata.ApiVersion + learnMore = @{ + url = "https://learn.microsoft.com/powershell/module/$rootModuleName".ToLower() + } + commands = @($cmdletInfo) + provider = $parameterSetMetadata.Provider + } + } +} + +$UXFolder = 'UX' +if (Test-Path $UXFolder) +{ + Remove-Item -Path $UXFolder -Recurse +} +$null = New-Item -ItemType Directory -Path $UXFolder + +foreach ($resourceType in $resourceTypes.Keys) +{ + $resourceTypeFileName = $resourceType -replace "/", "-" + if ($resourceTypeFileName -eq "") + { + continue + } + $resourceTypeInfo = $resourceTypes[$resourceType] + $provider = $resourceTypeInfo.provider + $providerFolder = "$UXFolder/$provider" + if (-not (Test-Path $providerFolder)) + { + $null = New-Item -ItemType Directory -Path $providerFolder + } + $resourceTypeInfo.Remove("provider") + $resourceTypeInfo | ConvertTo-Json -Depth 10 | Out-File "$providerFolder/$resourceTypeFileName.json" +} diff --git a/src/Resources/DataBoundary.Autorest/generated/Module.cs b/src/Resources/DataBoundary.Autorest/generated/Module.cs new file mode 100644 index 000000000000..500c866afe3f --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/Module.cs @@ -0,0 +1,202 @@ +// 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.DataBoundary +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 ArgumentCompleterDelegate = global::System.Func; + using GetTelemetryIdDelegate = global::System.Func; + using TelemetryDelegate = global::System.Action; + 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 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>; + using SanitizerDelegate = global::System.Action; + using GetTelemetryInfoDelegate = global::System.Func>; + + /// 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(); + + private static bool _init = false; + + private static readonly global::System.Object _initLock = new global::System.Object(); + + private static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module _instance; + + /// the ISendAsync pipeline instance + private Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.HttpPipeline _pipeline; + + /// the ISendAsync pipeline instance (when proxy is enabled) + private Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.HttpPipeline _pipelineWithProxy; + + private static readonly global::System.Object _singletonLock = new global::System.Object(); + + public bool _useProxy = false; + + 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.DataBoundary.DataBoundary 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; } + + /// The delegate to get the telemetry Id. + public GetTelemetryIdDelegate GetTelemetryId { get; set; } + + /// The delegate to get the telemetry info. + public GetTelemetryInfoDelegate GetTelemetryInfo { get; set; } + + /// the singleton of this module class + public static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module Instance { get { if (_instance == null) { lock (_singletonLock) { if (_instance == null) { _instance = new Module(); }}} return _instance; } } + + /// The Name of this module + public string Name => @"Az.DataBoundary"; + + /// 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.DataBoundary"; + + /// The delegate to call in WriteObject to sanitize the output object. + public SanitizerDelegate SanitizeOutput { get; set; } + + /// The delegate for creating a telemetry. + public TelemetryDelegate Telemetry { get; set; } + + /// The from the cmdlet + /// The HttpPipeline for the request + + partial void AfterCreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, ref Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.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. + /// a dict for extensible parameters + /// An instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.HttpPipeline for the remote call. + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.HttpPipeline CreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string processRecordId, string parameterSetName = null, global::System.Collections.Generic.IDictionary extensibleParameters = null) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.HttpPipeline pipeline = null; + BeforeCreatePipeline(invocationInfo, ref pipeline); + pipeline = (pipeline ?? (_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() + { + if (_init == false) + { + lock (_initLock) { + if (_init == false) { + 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(); + _init = true; + } + } + } + } + + /// Creates the module instance. + private Module() + { + // constructor + ClientAPI = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.DataBoundary(); + _handler.Proxy = _webProxy; + _pipeline = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient())); + _pipelineWithProxy = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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) + { + _useProxy = proxy != null; + if (proxy == null) + { + return; + } + // set the proxy configuration + _webProxy.Address = proxy; + _webProxy.BypassProxyOnLocal = false; + if (proxyUseDefaultCredentials) + { + _webProxy.Credentials = null; + _webProxy.UseDefaultCredentials = true; + } + else + { + _webProxy.UseDefaultCredentials = false; + _webProxy.Credentials = proxyCredential ?.GetNetworkCredential(); + } + } + + /// 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/Resources/DataBoundary.Autorest/generated/api/DataBoundary.cs b/src/Resources/DataBoundary.Autorest/generated/api/DataBoundary.cs new file mode 100644 index 000000000000..224a34422a7b --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/DataBoundary.cs @@ -0,0 +1,1307 @@ +// 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.DataBoundary +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// + /// Low-level API implementation for the DataBoundary service. + /// Provides APIs for data boundary operations. + /// + public partial class DataBoundary + { + + /// Get data boundary at specified scope + /// The scope at which the operation is performed. + /// 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.DataBoundary.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 DataBoundariesGetScope(string scope, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + var @default = @"default"; + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/" + + (scope) + + "/providers/Microsoft.Resources/dataBoundaries/" + + global::System.Uri.EscapeDataString(@default) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.DataBoundariesGetScope_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get data boundary at specified scope + /// + /// 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.DataBoundary.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 DataBoundariesGetScopeViaIdentity(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.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/(?[^/]+)/providers/Microsoft.Resources/dataBoundaries/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/{scope}/providers/Microsoft.Resources/dataBoundaries/{default}'"); + } + + // replace URI parameters with values from identity + var scope = _match.Groups["scope"].Value; + var @default = _match.Groups["default"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/" + + scope + + "/providers/Microsoft.Resources/dataBoundaries/" + + @default + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.DataBoundariesGetScope_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get data boundary at specified scope + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 DataBoundariesGetScopeViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/(?[^/]+)/providers/Microsoft.Resources/dataBoundaries/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/{scope}/providers/Microsoft.Resources/dataBoundaries/{default}'"); + } + + // replace URI parameters with values from identity + var scope = _match.Groups["scope"].Value; + var @default = _match.Groups["default"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/" + + scope + + "/providers/Microsoft.Resources/dataBoundaries/" + + @default + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.DataBoundariesGetScopeWithResult_Call (request, eventListener,sender); + } + } + + /// Get data boundary at specified scope + /// The scope at which the operation is performed. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 DataBoundariesGetScopeWithResult(string scope, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + var @default = @"default"; + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/" + + (scope) + + "/providers/Microsoft.Resources/dataBoundaries/" + + global::System.Uri.EscapeDataString(@default) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.DataBoundariesGetScopeWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 DataBoundariesGetScopeWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryDefinition.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// 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.DataBoundary.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 DataBoundariesGetScope_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.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Progress, "intentional placeholder", 100); 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.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryDefinition.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 scope at which the operation is performed. + /// 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 DataBoundariesGetScope_Validate(string scope, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(scope),scope); + await eventListener.AssertMinimumLength(nameof(scope),scope,1); + } + } + + /// Get data boundary of tenant. + /// 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.DataBoundary.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 DataBoundariesGetTenant(global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + var @default = @"default"; + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Resources/dataBoundaries/" + + global::System.Uri.EscapeDataString(@default) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.DataBoundariesGetTenant_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get data boundary of tenant. + /// + /// 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.DataBoundary.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 DataBoundariesGetTenantViaIdentity(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.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.Resources/dataBoundaries/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.Resources/dataBoundaries/{default}'"); + } + + // replace URI parameters with values from identity + var @default = _match.Groups["default"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Resources/dataBoundaries/" + + @default + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.DataBoundariesGetTenant_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get data boundary of tenant. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 DataBoundariesGetTenantViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.Resources/dataBoundaries/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.Resources/dataBoundaries/{default}'"); + } + + // replace URI parameters with values from identity + var @default = _match.Groups["default"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Resources/dataBoundaries/" + + @default + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.DataBoundariesGetTenantWithResult_Call (request, eventListener,sender); + } + } + + /// Get data boundary of tenant. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 DataBoundariesGetTenantWithResult(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + var @default = @"default"; + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Resources/dataBoundaries/" + + global::System.Uri.EscapeDataString(@default) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.DataBoundariesGetTenantWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 DataBoundariesGetTenantWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryDefinition.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// 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.DataBoundary.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 DataBoundariesGetTenant_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.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Progress, "intentional placeholder", 100); 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.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryDefinition.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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. + /// + /// 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 DataBoundariesGetTenant_Validate(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + + } + } + + /// Opt-in tenant to data boundary. + /// The data boundary to opt the tenant to. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// 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.DataBoundary.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DataBoundariesPut(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeUpdate) + { + var @default = @"default"; + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Resources/dataBoundaries/" + + global::System.Uri.EscapeDataString(@default) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).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.DataBoundary.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.DataBoundariesPut_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// Opt-in tenant to data boundary. + /// + /// The data boundary to opt the tenant to. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// 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.DataBoundary.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DataBoundariesPutViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.Resources/dataBoundaries/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.Resources/dataBoundaries/{default}'"); + } + + // replace URI parameters with values from identity + var @default = _match.Groups["default"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Resources/dataBoundaries/" + + @default + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).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.DataBoundary.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.DataBoundariesPut_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// Opt-in tenant to data boundary. + /// + /// The data boundary to opt the tenant to. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DataBoundariesPutViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition body, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.Resources/dataBoundaries/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.Resources/dataBoundaries/{default}'"); + } + + // replace URI parameters with values from identity + var @default = _match.Groups["default"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Resources/dataBoundaries/" + + @default + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).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.DataBoundary.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.DataBoundariesPutWithResult_Call (request, eventListener,sender); + } + } + + /// Opt-in tenant to data boundary. + /// Json string supplied to the DataBoundariesPut operation + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// 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.DataBoundary.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 DataBoundariesPutViaJsonString(global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + var @default = @"default"; + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Resources/dataBoundaries/" + + global::System.Uri.EscapeDataString(@default) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, 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.DataBoundary.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.DataBoundariesPut_Call (request, onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// Opt-in tenant to data boundary. + /// Json string supplied to the DataBoundariesPut operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 DataBoundariesPutViaJsonStringWithResult(global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + var @default = @"default"; + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Resources/dataBoundaries/" + + global::System.Uri.EscapeDataString(@default) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, 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.DataBoundary.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.DataBoundariesPutWithResult_Call (request, eventListener,sender); + } + } + + /// Opt-in tenant to data boundary. + /// The data boundary to opt the tenant to. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task DataBoundariesPutWithResult(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition body, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeUpdate) + { + var @default = @"default"; + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Resources/dataBoundaries/" + + global::System.Uri.EscapeDataString(@default) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).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.DataBoundary.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.DataBoundariesPutWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 DataBoundariesPutWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryDefinition.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryDefinition.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// 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 201 (Created). + /// 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.DataBoundary.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 DataBoundariesPut_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Progress, "intentional placeholder", 100); 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.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryDefinition.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onCreated(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryDefinition.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 data boundary to opt the tenant to. + /// 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 DataBoundariesPut_Validate(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition body, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Lists all of the available Microsoft.Resources REST API operations. + /// 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.DataBoundary.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(global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Resources/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Lists all of the available Microsoft.Resources REST API operations. + /// + /// 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.DataBoundary.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, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.Resources/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.Resources/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Resources/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Lists all of the available Microsoft.Resources REST API operations. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 OperationsListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.Resources/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.Resources/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Resources/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OperationsListWithResult_Call (request, eventListener,sender); + } + } + + /// Lists all of the available Microsoft.Resources REST API operations. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 OperationsListWithResult(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.Resources/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OperationsListWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 OperationsListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// 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.DataBoundary.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.DataBoundary.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Progress, "intentional placeholder", 100); 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.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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. + /// + /// 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(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + + } + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/Any.PowerShell.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/Any.PowerShell.cs new file mode 100644 index 000000000000..e402e0315a5f --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/Any.PowerShell.cs @@ -0,0 +1,156 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// Anything + [System.ComponentModel.TypeConverter(typeof(AnyTypeConverter))] + public partial class Any + { + + /// + /// 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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Any(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 Any(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.DataBoundary.Models.IAny DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Any(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.DataBoundary.Models.IAny DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Any(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.DataBoundary.Models.IAny FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Anything + [System.ComponentModel.TypeConverter(typeof(AnyTypeConverter))] + public partial interface IAny + + { + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/Any.TypeConverter.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/Any.TypeConverter.cs new file mode 100644 index 000000000000..3951a4d10abd --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/Any.TypeConverter.cs @@ -0,0 +1,146 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AnyTypeConverter : 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 type. + /// + /// 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.DataBoundary.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 into an instance of + /// + /// 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.DataBoundary.Models.IAny ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IAny).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Any.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Any.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Any.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/Resources/DataBoundary.Autorest/generated/api/Models/Any.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/Any.cs new file mode 100644 index 000000000000..2a272ac4740d --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/Any.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. +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// Anything + public partial class Any : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IAny, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IAnyInternal + { + + /// Creates an new instance. + public Any() + { + + } + } + /// Anything + public partial interface IAny : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IJsonSerializable + { + + } + /// Anything + internal partial interface IAnyInternal + + { + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/Any.json.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/Any.json.cs new file mode 100644 index 000000000000..6b2264eabbf6 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/Any.json.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. +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// Anything + public partial class Any + { + + /// + /// 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.DataBoundary.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization 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.DataBoundary.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.DataBoundary.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.DataBoundary.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject instance to deserialize from. + internal Any(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Models.IAny. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IAny. + public static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IAny FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json ? new Any(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.DataBoundary.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryDefinition.PowerShell.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryDefinition.PowerShell.cs new file mode 100644 index 000000000000..954f87967a9d --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryDefinition.PowerShell.cs @@ -0,0 +1,260 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// A data boundary definition. + [System.ComponentModel.TypeConverter(typeof(DataBoundaryDefinitionTypeConverter))] + public partial class DataBoundaryDefinition + { + + /// + /// 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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal DataBoundaryDefinition(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinitionInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinitionInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("DataBoundary")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinitionInternal)this).DataBoundary = (string) content.GetValueForProperty("DataBoundary",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinitionInternal)this).DataBoundary, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinitionInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinitionInternal)this).ProvisioningState, 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 DataBoundaryDefinition(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinitionInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinitionInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("DataBoundary")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinitionInternal)this).DataBoundary = (string) content.GetValueForProperty("DataBoundary",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinitionInternal)this).DataBoundary, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinitionInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinitionInternal)this).ProvisioningState, 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.DataBoundary.Models.IDataBoundaryDefinition DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new DataBoundaryDefinition(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.DataBoundary.Models.IDataBoundaryDefinition DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new DataBoundaryDefinition(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.DataBoundary.Models.IDataBoundaryDefinition FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// A data boundary definition. + [System.ComponentModel.TypeConverter(typeof(DataBoundaryDefinitionTypeConverter))] + public partial interface IDataBoundaryDefinition + + { + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryDefinition.TypeConverter.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryDefinition.TypeConverter.cs new file mode 100644 index 000000000000..f27b2e803d12 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryDefinition.TypeConverter.cs @@ -0,0 +1,147 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class DataBoundaryDefinitionTypeConverter : 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 + /// type. + /// + /// 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.DataBoundary.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 into an instance of + /// + /// 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.DataBoundary.Models.IDataBoundaryDefinition ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return DataBoundaryDefinition.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return DataBoundaryDefinition.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return DataBoundaryDefinition.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/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryDefinition.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryDefinition.cs new file mode 100644 index 000000000000..03a59ccf9ede --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryDefinition.cs @@ -0,0 +1,167 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// A data boundary definition. + public partial class DataBoundaryDefinition : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinitionInternal, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ProxyResource(); + + /// The data boundary definition. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inlined)] + public string DataBoundary { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryPropertiesInternal)Property).DataBoundary; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryPropertiesInternal)Property).DataBoundary = value ?? null; } + + /// + /// Fully qualified resource ID for the resource. E.g. "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}" + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).Id; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryProperties Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinitionInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinitionInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryPropertiesInternal)Property).ProvisioningState = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).Name = value; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).SystemData = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).Type = value; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryProperties _property; + + /// Data boundary properties + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryProperties()); set => this._property = value; } + + /// Denotes the state of provisioning. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).SystemData; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public DataBoundaryDefinition() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// A data boundary definition. + public partial interface IDataBoundaryDefinition : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IProxyResource + { + /// The data boundary definition. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The data boundary definition.", + SerializedName = @"dataBoundary", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("NotDefined", "Global", "EU")] + string DataBoundary { get; set; } + /// Denotes the state of provisioning. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Denotes the state of provisioning.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("Accepted", "Running", "Creating", "Canceled", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + + } + /// A data boundary definition. + internal partial interface IDataBoundaryDefinitionInternal : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IProxyResourceInternal + { + /// The data boundary definition. + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("NotDefined", "Global", "EU")] + string DataBoundary { get; set; } + /// Data boundary properties + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryProperties Property { get; set; } + /// Denotes the state of provisioning. + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("Accepted", "Running", "Creating", "Canceled", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryDefinition.json.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryDefinition.json.cs new file mode 100644 index 000000000000..298bd9fbcf0e --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryDefinition.json.cs @@ -0,0 +1,110 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// A data boundary definition. + public partial class DataBoundaryDefinition + { + + /// + /// 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.DataBoundary.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization 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.DataBoundary.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.DataBoundary.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.DataBoundary.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject instance to deserialize from. + internal DataBoundaryDefinition(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryProperties.FromJson(__jsonProperties) : _property;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json ? new DataBoundaryDefinition(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.DataBoundary.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __proxyResource?.ToJson(container, serializationMode); + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryIdentity.PowerShell.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryIdentity.PowerShell.cs new file mode 100644 index 000000000000..f330efaaffa8 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryIdentity.PowerShell.cs @@ -0,0 +1,178 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(DataBoundaryIdentityTypeConverter))] + public partial class DataBoundaryIdentity + { + + /// + /// 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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal DataBoundaryIdentity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Default")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentityInternal)this).Default = (string) content.GetValueForProperty("Default",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentityInternal)this).Default, global::System.Convert.ToString); + } + if (content.Contains("Scope")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentityInternal)this).Scope = (string) content.GetValueForProperty("Scope",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentityInternal)this).Scope, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentityInternal)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 DataBoundaryIdentity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Default")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentityInternal)this).Default = (string) content.GetValueForProperty("Default",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentityInternal)this).Default, global::System.Convert.ToString); + } + if (content.Contains("Scope")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentityInternal)this).Scope = (string) content.GetValueForProperty("Scope",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentityInternal)this).Scope, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentityInternal)this).Id, 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.DataBoundary.Models.IDataBoundaryIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new DataBoundaryIdentity(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.DataBoundary.Models.IDataBoundaryIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new DataBoundaryIdentity(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.DataBoundary.Models.IDataBoundaryIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + [System.ComponentModel.TypeConverter(typeof(DataBoundaryIdentityTypeConverter))] + public partial interface IDataBoundaryIdentity + + { + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryIdentity.TypeConverter.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryIdentity.TypeConverter.cs new file mode 100644 index 000000000000..0c4204f630e2 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryIdentity.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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class DataBoundaryIdentityTypeConverter : 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 + /// type. + /// + /// 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.DataBoundary.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 into an instance of + /// + /// 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.DataBoundary.Models.IDataBoundaryIdentity 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 DataBoundaryIdentity { Id = sourceValue }; + } + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return DataBoundaryIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return DataBoundaryIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return DataBoundaryIdentity.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/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryIdentity.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryIdentity.cs new file mode 100644 index 000000000000..6a99f8ebea62 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryIdentity.cs @@ -0,0 +1,93 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + public partial class DataBoundaryIdentity : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentity, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentityInternal + { + + /// Backing field for property. + private string _default; + + /// Default string modeled as parameter for auto generation to work correctly. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string Default { get => this._default; set => this._default = value; } + + /// Backing field for property. + private string _id; + + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Backing field for property. + private string _scope; + + /// The scope at which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string Scope { get => this._scope; set => this._scope = value; } + + /// Creates an new instance. + public DataBoundaryIdentity() + { + + } + } + public partial interface IDataBoundaryIdentity : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IJsonSerializable + { + /// Default string modeled as parameter for auto generation to work correctly. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Default string modeled as parameter for auto generation to work correctly.", + SerializedName = @"default", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("default")] + string Default { get; set; } + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource identity path", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// The scope at which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The scope at which the operation is performed.", + SerializedName = @"scope", + PossibleTypes = new [] { typeof(string) })] + string Scope { get; set; } + + } + internal partial interface IDataBoundaryIdentityInternal + + { + /// Default string modeled as parameter for auto generation to work correctly. + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("default")] + string Default { get; set; } + /// Resource identity path + string Id { get; set; } + /// The scope at which the operation is performed. + string Scope { get; set; } + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryIdentity.json.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryIdentity.json.cs new file mode 100644 index 000000000000..2619fb179d05 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryIdentity.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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + public partial class DataBoundaryIdentity + { + + /// + /// 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.DataBoundary.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization 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.DataBoundary.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.DataBoundary.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.DataBoundary.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject instance to deserialize from. + internal DataBoundaryIdentity(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_default = If( json?.PropertyT("default"), out var __jsonDefault) ? (string)__jsonDefault : (string)_default;} + {_scope = If( json?.PropertyT("scope"), out var __jsonScope) ? (string)__jsonScope : (string)_scope;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json ? new DataBoundaryIdentity(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.DataBoundary.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._default)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._default.ToString()) : null, "default" ,container.Add ); + AddIf( null != (((object)this._scope)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._scope.ToString()) : null, "scope" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryProperties.PowerShell.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryProperties.PowerShell.cs new file mode 100644 index 000000000000..808ffc092cb0 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryProperties.PowerShell.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. +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// Data boundary properties + [System.ComponentModel.TypeConverter(typeof(DataBoundaryPropertiesTypeConverter))] + public partial class DataBoundaryProperties + { + + /// + /// 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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal DataBoundaryProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DataBoundary")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryPropertiesInternal)this).DataBoundary = (string) content.GetValueForProperty("DataBoundary",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryPropertiesInternal)this).DataBoundary, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryPropertiesInternal)this).ProvisioningState, 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 DataBoundaryProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("DataBoundary")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryPropertiesInternal)this).DataBoundary = (string) content.GetValueForProperty("DataBoundary",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryPropertiesInternal)this).DataBoundary, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryPropertiesInternal)this).ProvisioningState, 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.DataBoundary.Models.IDataBoundaryProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new DataBoundaryProperties(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.DataBoundary.Models.IDataBoundaryProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new DataBoundaryProperties(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.DataBoundary.Models.IDataBoundaryProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Data boundary properties + [System.ComponentModel.TypeConverter(typeof(DataBoundaryPropertiesTypeConverter))] + public partial interface IDataBoundaryProperties + + { + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryProperties.TypeConverter.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryProperties.TypeConverter.cs new file mode 100644 index 000000000000..b36e383184c9 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryProperties.TypeConverter.cs @@ -0,0 +1,147 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class DataBoundaryPropertiesTypeConverter : 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 + /// type. + /// + /// 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.DataBoundary.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 into an instance of + /// + /// 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.DataBoundary.Models.IDataBoundaryProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return DataBoundaryProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return DataBoundaryProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return DataBoundaryProperties.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/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryProperties.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryProperties.cs new file mode 100644 index 000000000000..efe398beda45 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryProperties.cs @@ -0,0 +1,81 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// Data boundary properties + public partial class DataBoundaryProperties : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryProperties, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryPropertiesInternal + { + + /// Backing field for property. + private string _dataBoundary; + + /// The data boundary definition. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string DataBoundary { get => this._dataBoundary; set => this._dataBoundary = value; } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// Denotes the state of provisioning. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Creates an new instance. + public DataBoundaryProperties() + { + + } + } + /// Data boundary properties + public partial interface IDataBoundaryProperties : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IJsonSerializable + { + /// The data boundary definition. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"The data boundary definition.", + SerializedName = @"dataBoundary", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("NotDefined", "Global", "EU")] + string DataBoundary { get; set; } + /// Denotes the state of provisioning. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Denotes the state of provisioning.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("Accepted", "Running", "Creating", "Canceled", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; } + + } + /// Data boundary properties + internal partial interface IDataBoundaryPropertiesInternal + + { + /// The data boundary definition. + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("NotDefined", "Global", "EU")] + string DataBoundary { get; set; } + /// Denotes the state of provisioning. + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("Accepted", "Running", "Creating", "Canceled", "Failed", "Succeeded", "Updating")] + string ProvisioningState { get; set; } + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryProperties.json.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryProperties.json.cs new file mode 100644 index 000000000000..f20fd67ff193 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/DataBoundaryProperties.json.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. +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// Data boundary properties + public partial class DataBoundaryProperties + { + + /// + /// 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.DataBoundary.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization 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.DataBoundary.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.DataBoundary.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.DataBoundary.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject instance to deserialize from. + internal DataBoundaryProperties(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_dataBoundary = If( json?.PropertyT("dataBoundary"), out var __jsonDataBoundary) ? (string)__jsonDataBoundary : (string)_dataBoundary;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json ? new DataBoundaryProperties(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.DataBoundary.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._dataBoundary)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._dataBoundary.ToString()) : null, "dataBoundary" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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/Resources/DataBoundary.Autorest/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs new file mode 100644 index 000000000000..9ea135c6ee05 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorAdditionalInfo.PowerShell.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. +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// The resource management error additional info. + [System.ComponentModel.TypeConverter(typeof(ErrorAdditionalInfoTypeConverter))] + public partial class ErrorAdditionalInfo + { + + /// + /// 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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, 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.DataBoundary.Models.IErrorAdditionalInfo DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorAdditionalInfo(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.DataBoundary.Models.IErrorAdditionalInfo DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorAdditionalInfo(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorAdditionalInfo(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.AnyTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorAdditionalInfo(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.AnyTypeConverter.ConvertFrom); + } + 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.DataBoundary.Models.IErrorAdditionalInfo FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The resource management error additional info. + [System.ComponentModel.TypeConverter(typeof(ErrorAdditionalInfoTypeConverter))] + public partial interface IErrorAdditionalInfo + + { + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs new file mode 100644 index 000000000000..ae78afba5221 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs @@ -0,0 +1,147 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorAdditionalInfoTypeConverter : 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 + /// type. + /// + /// 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.DataBoundary.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 into an instance of + /// + /// 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.DataBoundary.Models.IErrorAdditionalInfo ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfo).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorAdditionalInfo.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorAdditionalInfo.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorAdditionalInfo.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/Resources/DataBoundary.Autorest/generated/api/Models/ErrorAdditionalInfo.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorAdditionalInfo.cs new file mode 100644 index 000000000000..1cc7624e992f --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorAdditionalInfo.cs @@ -0,0 +1,80 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// The resource management error additional info. + public partial class ErrorAdditionalInfo : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfo, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfoInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IAny _info; + + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IAny Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.Any()); } + + /// Internal Acessors for Info + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IAny Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfoInternal.Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.Any()); set { {_info = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfoInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _type; + + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public ErrorAdditionalInfo() + { + + } + } + /// The resource management error additional info. + public partial interface IErrorAdditionalInfo : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IJsonSerializable + { + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The additional info.", + SerializedName = @"info", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IAny) })] + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IAny Info { get; } + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The additional info type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// The resource management error additional info. + internal partial interface IErrorAdditionalInfoInternal + + { + /// The additional info. + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IAny Info { get; set; } + /// The additional info type. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorAdditionalInfo.json.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorAdditionalInfo.json.cs new file mode 100644 index 000000000000..8389bf02ecc4 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorAdditionalInfo.json.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. +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// The resource management error additional info. + public partial class ErrorAdditionalInfo + { + + /// + /// 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.DataBoundary.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization 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.DataBoundary.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.DataBoundary.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.DataBoundary.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorAdditionalInfo(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + {_info = If( json?.PropertyT("info"), out var __jsonInfo) ? Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.Any.FromJson(__jsonInfo) : _info;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfo. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfo. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfo FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json ? new ErrorAdditionalInfo(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.DataBoundary.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._info ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) this._info.ToJson(null,serializationMode) : null, "info" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorDetail.PowerShell.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorDetail.PowerShell.cs new file mode 100644 index 000000000000..c72c0e183cb7 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorDetail.PowerShell.cs @@ -0,0 +1,196 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// The error detail. + [System.ComponentModel.TypeConverter(typeof(ErrorDetailTypeConverter))] + public partial class ErrorDetail + { + + /// + /// 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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, 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.DataBoundary.Models.IErrorDetail DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorDetail(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.DataBoundary.Models.IErrorDetail DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorDetail(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorDetail(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorDetail(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + 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.DataBoundary.Models.IErrorDetail FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The error detail. + [System.ComponentModel.TypeConverter(typeof(ErrorDetailTypeConverter))] + public partial interface IErrorDetail + + { + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorDetail.TypeConverter.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorDetail.TypeConverter.cs new file mode 100644 index 000000000000..fb6d928e6783 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorDetail.TypeConverter.cs @@ -0,0 +1,147 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorDetailTypeConverter : 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 + /// type. + /// + /// 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.DataBoundary.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 into an instance of + /// + /// 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.DataBoundary.Models.IErrorDetail ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetail).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorDetail.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorDetail.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorDetail.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/Resources/DataBoundary.Autorest/generated/api/Models/ErrorDetail.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorDetail.cs new file mode 100644 index 000000000000..2641d816ee1f --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorDetail.cs @@ -0,0 +1,149 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// The error detail. + public partial class ErrorDetail : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetail, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _additionalInfo; + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public System.Collections.Generic.List AdditionalInfo { get => this._additionalInfo; } + + /// Backing field for property. + private string _code; + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string Code { get => this._code; } + + /// Backing field for property. + private System.Collections.Generic.List _detail; + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public System.Collections.Generic.List Detail { get => this._detail; } + + /// Backing field for property. + private string _message; + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal.AdditionalInfo { get => this._additionalInfo; set { {_additionalInfo = value;} } } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal.Code { get => this._code; set { {_code = value;} } } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal.Detail { get => this._detail; set { {_detail = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal.Message { get => this._message; set { {_message = value;} } } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal.Target { get => this._target; set { {_target = value;} } } + + /// Backing field for property. + private string _target; + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string Target { get => this._target; } + + /// Creates an new instance. + public ErrorDetail() + { + + } + } + /// The error detail. + public partial interface IErrorDetail : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error additional info.", + SerializedName = @"additionalInfo", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error details.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string Target { get; } + + } + /// The error detail. + internal partial interface IErrorDetailInternal + + { + /// The error additional info. + System.Collections.Generic.List AdditionalInfo { get; set; } + /// The error code. + string Code { get; set; } + /// The error details. + System.Collections.Generic.List Detail { get; set; } + /// The error message. + string Message { get; set; } + /// The error target. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorDetail.json.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorDetail.json.cs new file mode 100644 index 000000000000..34ec92249baa --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorDetail.json.cs @@ -0,0 +1,147 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// The error detail. + public partial class ErrorDetail + { + + /// + /// 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.DataBoundary.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization 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.DataBoundary.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.DataBoundary.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.DataBoundary.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorDetail(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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;} + {_target = If( json?.PropertyT("target"), out var __jsonTarget) ? (string)__jsonTarget : (string)_target;} + {_detail = If( json?.PropertyT("details"), out var __jsonDetails) ? If( __jsonDetails as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetail) (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorDetail.FromJson(__u) )) ))() : null : _detail;} + {_additionalInfo = If( json?.PropertyT("additionalInfo"), out var __jsonAdditionalInfo) ? If( __jsonAdditionalInfo as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonArray, out var __q) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__q, (__p)=>(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfo) (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorAdditionalInfo.FromJson(__p) )) ))() : null : _additionalInfo;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetail. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetail. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetail FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json ? new ErrorDetail(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.DataBoundary.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._target)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._target.ToString()) : null, "target" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._detail) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.XNodeArray(); + foreach( var __x in this._detail ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("details",__w); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._additionalInfo) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.XNodeArray(); + foreach( var __s in this._additionalInfo ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("additionalInfo",__r); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorResponse.PowerShell.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorResponse.PowerShell.cs new file mode 100644 index 000000000000..4f4d27e81426 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorResponse.PowerShell.cs @@ -0,0 +1,208 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows + /// the OData error response format.). + /// + [System.ComponentModel.TypeConverter(typeof(ErrorResponseTypeConverter))] + public partial class ErrorResponse + { + + /// + /// 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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, 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.DataBoundary.Models.IErrorResponse DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorResponse(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.DataBoundary.Models.IErrorResponse DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorResponse(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorResponse(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorResponse(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + 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.DataBoundary.Models.IErrorResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows + /// the OData error response format.). + [System.ComponentModel.TypeConverter(typeof(ErrorResponseTypeConverter))] + public partial interface IErrorResponse + + { + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorResponse.TypeConverter.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorResponse.TypeConverter.cs new file mode 100644 index 000000000000..113c48cb5d9f --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorResponse.TypeConverter.cs @@ -0,0 +1,147 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorResponseTypeConverter : 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 + /// type. + /// + /// 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.DataBoundary.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 into an instance of + /// + /// 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.DataBoundary.Models.IErrorResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorResponse.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorResponse.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/Resources/DataBoundary.Autorest/generated/api/Models/ErrorResponse.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorResponse.cs new file mode 100644 index 000000000000..fb1318379ee8 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorResponse.cs @@ -0,0 +1,151 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows + /// the OData error response format.). + /// + public partial class ErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal + { + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)Error).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)Error).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)Error).Detail; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetail _error; + + /// The error object. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetail Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorDetail()); set => this._error = value; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)Error).Message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)Error).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)Error).AdditionalInfo = value; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)Error).Code = value; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)Error).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)Error).Detail = value; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorDetail()); set { {_error = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)Error).Message = value; } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponseInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)Error).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)Error).Target = value; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetailInternal)Error).Target; } + + /// Creates an new instance. + public ErrorResponse() + { + + } + } + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows + /// the OData error response format.). + public partial interface IErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error additional info.", + SerializedName = @"additionalInfo", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error details.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string Target { get; } + + } + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows + /// the OData error response format.). + internal partial interface IErrorResponseInternal + + { + /// The error additional info. + System.Collections.Generic.List AdditionalInfo { get; set; } + /// The error code. + string Code { get; set; } + /// The error details. + System.Collections.Generic.List Detail { get; set; } + /// The error object. + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorDetail Error { get; set; } + /// The error message. + string Message { get; set; } + /// The error target. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorResponse.json.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorResponse.json.cs new file mode 100644 index 000000000000..c5ceeb34e458 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/ErrorResponse.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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows + /// the OData error response format.). + /// + public partial class ErrorResponse + { + + /// + /// 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.DataBoundary.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization 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.DataBoundary.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.DataBoundary.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.DataBoundary.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorResponse(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_error = If( json?.PropertyT("error"), out var __jsonError) ? Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ErrorDetail.FromJson(__jsonError) : _error;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json ? new ErrorResponse(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.DataBoundary.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) this._error.ToJson(null,serializationMode) : null, "error" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/Operation.PowerShell.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/Operation.PowerShell.cs new file mode 100644 index 000000000000..c6b29c525af1 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/Operation.PowerShell.cs @@ -0,0 +1,230 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + [System.ComponentModel.TypeConverter(typeof(OperationTypeConverter))] + public partial class Operation + { + + /// + /// 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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, 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.DataBoundary.Models.IOperation DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Operation(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.DataBoundary.Models.IOperation DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Operation(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.DataBoundary.Models.IOperation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Operation(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Display")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).DisplayDescription, 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 Operation(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Display")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal)this).DisplayDescription, 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.DataBoundary.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Details of a REST API operation, returned from the Resource Provider Operations API + [System.ComponentModel.TypeConverter(typeof(OperationTypeConverter))] + public partial interface IOperation + + { + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/Operation.TypeConverter.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/Operation.TypeConverter.cs new file mode 100644 index 000000000000..327f45241d2b --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/Operation.TypeConverter.cs @@ -0,0 +1,146 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationTypeConverter : 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 type. + /// + /// 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.DataBoundary.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 into an instance of + /// + /// 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.DataBoundary.Models.IOperation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperation).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Operation.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Operation.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Operation.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/Resources/DataBoundary.Autorest/generated/api/Models/Operation.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/Operation.cs new file mode 100644 index 000000000000..778216200236 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/Operation.cs @@ -0,0 +1,284 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + public partial class Operation : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperation, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal + { + + /// Backing field for property. + private string _actionType; + + /// + /// Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string ActionType { get => this._actionType; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplay _display; + + /// Localized display information for this particular operation. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplay Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.OperationDisplay()); set => this._display = value; } + + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inlined)] + public string DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)Display).Description; } + + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inlined)] + public string DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)Display).Operation; } + + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inlined)] + public string DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)Display).Provider; } + + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inlined)] + public string DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)Display).Resource; } + + /// Backing field for property. + private bool? _isDataAction; + + /// + /// Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for ARM/control-plane + /// operations. + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public bool? IsDataAction { get => this._isDataAction; } + + /// Internal Acessors for ActionType + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal.ActionType { get => this._actionType; set { {_actionType = value;} } } + + /// Internal Acessors for Display + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplay Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal.Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.OperationDisplay()); set { {_display = value;} } } + + /// Internal Acessors for DisplayDescription + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal.DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)Display).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)Display).Description = value; } + + /// Internal Acessors for DisplayOperation + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal.DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)Display).Operation; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)Display).Operation = value; } + + /// Internal Acessors for DisplayProvider + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal.DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)Display).Provider; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)Display).Provider = value; } + + /// Internal Acessors for DisplayResource + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal.DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)Display).Resource; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)Display).Resource = value; } + + /// Internal Acessors for IsDataAction + bool? Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal.IsDataAction { get => this._isDataAction; set { {_isDataAction = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Origin + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationInternal.Origin { get => this._origin; set { {_origin = value;} } } + + /// Backing field for property. + private string _name; + + /// + /// The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + /// "Microsoft.Compute/virtualMachines/capture/action" + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private string _origin; + + /// + /// The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is + /// "user,system" + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string Origin { get => this._origin; } + + /// Creates an new instance. + public Operation() + { + + } + } + /// Details of a REST API operation, returned from the Resource Provider Operations API + public partial interface IOperation : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IJsonSerializable + { + /// + /// Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Enum. Indicates the action type. ""Internal"" refers to actions that are for internal only APIs.", + SerializedName = @"actionType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; } + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The short, localized friendly description of the operation; suitable for tool tips and detailed views.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string DisplayDescription { get; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The concise, localized friendly name for the operation; suitable for dropdowns. E.g. ""Create or Update Virtual Machine"", ""Restart Virtual Machine"".", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string DisplayOperation { get; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly form of the resource provider name, e.g. ""Microsoft Monitoring Insights"" or ""Microsoft Compute"".", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string DisplayProvider { get; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly name of the resource type related to this operation. E.g. ""Virtual Machines"" or ""Job Schedule Collections"".", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string DisplayResource { get; } + /// + /// Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for ARM/control-plane + /// operations. + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Whether the operation applies to data-plane. This is ""true"" for data-plane operations and ""false"" for ARM/control-plane operations.", + SerializedName = @"isDataAction", + PossibleTypes = new [] { typeof(bool) })] + bool? IsDataAction { get; } + /// + /// The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + /// "Microsoft.Compute/virtualMachines/capture/action" + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the operation, as per Resource-Based Access Control (RBAC). Examples: ""Microsoft.Compute/virtualMachines/write"", ""Microsoft.Compute/virtualMachines/capture/action""", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// + /// The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is + /// "user,system" + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is ""user,system""", + SerializedName = @"origin", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("user", "system", "user,system")] + string Origin { get; } + + } + /// Details of a REST API operation, returned from the Resource Provider Operations API + internal partial interface IOperationInternal + + { + /// + /// Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; set; } + /// Localized display information for this particular operation. + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplay Display { get; set; } + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + string DisplayDescription { get; set; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + string DisplayOperation { get; set; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + string DisplayProvider { get; set; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + string DisplayResource { get; set; } + /// + /// Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for ARM/control-plane + /// operations. + /// + bool? IsDataAction { get; set; } + /// + /// The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + /// "Microsoft.Compute/virtualMachines/capture/action" + /// + string Name { get; set; } + /// + /// The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is + /// "user,system" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("user", "system", "user,system")] + string Origin { get; set; } + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/Operation.json.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/Operation.json.cs new file mode 100644 index 000000000000..76d48affee05 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/Operation.json.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. +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + public partial class Operation + { + + /// + /// 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.DataBoundary.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization 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.DataBoundary.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.DataBoundary.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.DataBoundary.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperation. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperation. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperation FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json ? new Operation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject instance to deserialize from. + internal Operation(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Models.OperationDisplay.FromJson(__jsonDisplay) : _display;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_isDataAction = If( json?.PropertyT("isDataAction"), out var __jsonIsDataAction) ? (bool?)__jsonIsDataAction : _isDataAction;} + {_origin = If( json?.PropertyT("origin"), out var __jsonOrigin) ? (string)__jsonOrigin : (string)_origin;} + {_actionType = If( json?.PropertyT("actionType"), out var __jsonActionType) ? (string)__jsonActionType : (string)_actionType;} + 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.DataBoundary.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._display ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) this._display.ToJson(null,serializationMode) : null, "display" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._isDataAction ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonBoolean((bool)this._isDataAction) : null, "isDataAction" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._origin)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._origin.ToString()) : null, "origin" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._actionType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._actionType.ToString()) : null, "actionType" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationDisplay.PowerShell.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationDisplay.PowerShell.cs new file mode 100644 index 000000000000..660d3c16f1e2 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationDisplay.PowerShell.cs @@ -0,0 +1,188 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// Localized display information for this particular operation. + [System.ComponentModel.TypeConverter(typeof(OperationDisplayTypeConverter))] + public partial class OperationDisplay + { + + /// + /// 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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, 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.DataBoundary.Models.IOperationDisplay DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationDisplay(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.DataBoundary.Models.IOperationDisplay DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationDisplay(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.DataBoundary.Models.IOperationDisplay FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationDisplay(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Provider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)this).Description, 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 OperationDisplay(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Provider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal)this).Description, 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.DataBoundary.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Localized display information for this particular operation. + [System.ComponentModel.TypeConverter(typeof(OperationDisplayTypeConverter))] + public partial interface IOperationDisplay + + { + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationDisplay.TypeConverter.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationDisplay.TypeConverter.cs new file mode 100644 index 000000000000..385948b4e341 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationDisplay.TypeConverter.cs @@ -0,0 +1,147 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationDisplayTypeConverter : 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 + /// type. + /// + /// 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.DataBoundary.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 into an instance of + /// + /// 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.DataBoundary.Models.IOperationDisplay ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplay).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationDisplay.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationDisplay.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationDisplay.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/Resources/DataBoundary.Autorest/generated/api/Models/OperationDisplay.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationDisplay.cs new file mode 100644 index 000000000000..21dfdf329aa4 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationDisplay.cs @@ -0,0 +1,153 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// Localized display information for this particular operation. + public partial class OperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplay, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal + { + + /// Backing field for property. + private string _description; + + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string Description { get => this._description; } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal.Description { get => this._description; set { {_description = value;} } } + + /// Internal Acessors for Operation + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal.Operation { get => this._operation; set { {_operation = value;} } } + + /// Internal Acessors for Provider + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal.Provider { get => this._provider; set { {_provider = value;} } } + + /// Internal Acessors for Resource + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplayInternal.Resource { get => this._resource; set { {_resource = value;} } } + + /// Backing field for property. + private string _operation; + + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string Operation { get => this._operation; } + + /// Backing field for property. + private string _provider; + + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string Provider { get => this._provider; } + + /// Backing field for property. + private string _resource; + + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string Resource { get => this._resource; } + + /// Creates an new instance. + public OperationDisplay() + { + + } + } + /// Localized display information for this particular operation. + public partial interface IOperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IJsonSerializable + { + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The short, localized friendly description of the operation; suitable for tool tips and detailed views.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The concise, localized friendly name for the operation; suitable for dropdowns. E.g. ""Create or Update Virtual Machine"", ""Restart Virtual Machine"".", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string Operation { get; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly form of the resource provider name, e.g. ""Microsoft Monitoring Insights"" or ""Microsoft Compute"".", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string Provider { get; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly name of the resource type related to this operation. E.g. ""Virtual Machines"" or ""Job Schedule Collections"".", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string Resource { get; } + + } + /// Localized display information for this particular operation. + internal partial interface IOperationDisplayInternal + + { + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + string Description { get; set; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + string Operation { get; set; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + string Provider { get; set; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + string Resource { get; set; } + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationDisplay.json.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationDisplay.json.cs new file mode 100644 index 000000000000..b8e1d89e519d --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationDisplay.json.cs @@ -0,0 +1,126 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// Localized display information for this particular operation. + public partial class OperationDisplay + { + + /// + /// 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.DataBoundary.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization 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.DataBoundary.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.DataBoundary.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.DataBoundary.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplay. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplay. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationDisplay FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json ? new OperationDisplay(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject instance to deserialize from. + internal OperationDisplay(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_provider = If( json?.PropertyT("provider"), out var __jsonProvider) ? (string)__jsonProvider : (string)_provider;} + {_resource = If( json?.PropertyT("resource"), out var __jsonResource) ? (string)__jsonResource : (string)_resource;} + {_operation = If( json?.PropertyT("operation"), out var __jsonOperation) ? (string)__jsonOperation : (string)_operation;} + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)_description;} + 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.DataBoundary.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provider)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._provider.ToString()) : null, "provider" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resource)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._resource.ToString()) : null, "resource" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._operation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._operation.ToString()) : null, "operation" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationListResult.PowerShell.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationListResult.PowerShell.cs new file mode 100644 index 000000000000..7f85281d3dfd --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationListResult.PowerShell.cs @@ -0,0 +1,176 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + /// + [System.ComponentModel.TypeConverter(typeof(OperationListResultTypeConverter))] + public partial class OperationListResult + { + + /// + /// 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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, 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.DataBoundary.Models.IOperationListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationListResult(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.DataBoundary.Models.IOperationListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationListResult(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.DataBoundary.Models.IOperationListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResultInternal)this).NextLink, 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 OperationListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResultInternal)this).NextLink, 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.DataBoundary.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + [System.ComponentModel.TypeConverter(typeof(OperationListResultTypeConverter))] + public partial interface IOperationListResult + + { + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationListResult.TypeConverter.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationListResult.TypeConverter.cs new file mode 100644 index 000000000000..3d7317a1bf55 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationListResult.TypeConverter.cs @@ -0,0 +1,147 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationListResultTypeConverter : 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 + /// type. + /// + /// 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.DataBoundary.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 into an instance of + /// + /// 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.DataBoundary.Models.IOperationListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationListResult.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/Resources/DataBoundary.Autorest/generated/api/Models/OperationListResult.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationListResult.cs new file mode 100644 index 000000000000..cad083caa569 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationListResult.cs @@ -0,0 +1,85 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + /// + public partial class OperationListResult : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResult, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResultInternal + { + + /// Internal Acessors for NextLink + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResultInternal.NextLink { get => this._nextLink; set { {_nextLink = value;} } } + + /// Internal Acessors for Value + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResultInternal.Value { get => this._value; set { {_value = value;} } } + + /// Backing field for property. + private string _nextLink; + + /// URL to get the next set of operation list results (if there are any). + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// List of operations supported by the resource provider + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; } + + /// Creates an new instance. + public OperationListResult() + { + + } + } + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + public partial interface IOperationListResult : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IJsonSerializable + { + /// URL to get the next set of operation list results (if there are any). + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"URL to get the next set of operation list results (if there are any).", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; } + /// List of operations supported by the resource provider + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"List of operations supported by the resource provider", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperation) })] + System.Collections.Generic.List Value { get; } + + } + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + internal partial interface IOperationListResultInternal + + { + /// URL to get the next set of operation list results (if there are any). + string NextLink { get; set; } + /// List of operations supported by the resource provider + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationListResult.json.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationListResult.json.cs new file mode 100644 index 000000000000..7aca9baf8b36 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/OperationListResult.json.cs @@ -0,0 +1,127 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + /// + public partial class OperationListResult + { + + /// + /// 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.DataBoundary.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization 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.DataBoundary.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.DataBoundary.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.DataBoundary.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json ? new OperationListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject instance to deserialize from. + internal OperationListResult(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperation) (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.Operation.FromJson(__u) )) ))() : null : _value;} + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)_nextLink;} + 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.DataBoundary.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/ProxyResource.PowerShell.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/ProxyResource.PowerShell.cs new file mode 100644 index 000000000000..1b50a170a193 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/ProxyResource.PowerShell.cs @@ -0,0 +1,238 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// + /// The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location + /// + [System.ComponentModel.TypeConverter(typeof(ProxyResourceTypeConverter))] + public partial class ProxyResource + { + + /// + /// 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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, 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.DataBoundary.Models.IProxyResource DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ProxyResource(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.DataBoundary.Models.IProxyResource DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ProxyResource(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.DataBoundary.Models.IProxyResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ProxyResource(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)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 ProxyResource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Type, 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.DataBoundary.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location + [System.ComponentModel.TypeConverter(typeof(ProxyResourceTypeConverter))] + public partial interface IProxyResource + + { + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/ProxyResource.TypeConverter.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/ProxyResource.TypeConverter.cs new file mode 100644 index 000000000000..76b7fd602176 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/ProxyResource.TypeConverter.cs @@ -0,0 +1,147 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ProxyResourceTypeConverter : 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 + /// type. + /// + /// 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.DataBoundary.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 into an instance of + /// + /// 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.DataBoundary.Models.IProxyResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IProxyResource).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ProxyResource.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ProxyResource.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ProxyResource.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/Resources/DataBoundary.Autorest/generated/api/Models/ProxyResource.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/ProxyResource.cs new file mode 100644 index 000000000000..207508f22c28 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/ProxyResource.cs @@ -0,0 +1,112 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// + /// The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location + /// + public partial class ProxyResource : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IProxyResource, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IProxyResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.Resource(); + + /// + /// Fully qualified resource ID for the resource. E.g. "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}" + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).Id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).Name = value; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).SystemData = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).Type = value; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).Name; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).SystemData; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).SystemDataCreatedBy = value ?? null; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).SystemDataCreatedByType = value ?? null; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).SystemDataLastModifiedBy = value ?? null; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).SystemDataLastModifiedByType = value ?? null; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)__resource).Type; } + + /// Creates an new instance. + public ProxyResource() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__resource), __resource); + await eventListener.AssertObjectIsValid(nameof(__resource), __resource); + } + } + /// The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location + public partial interface IProxyResource : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResource + { + + } + /// The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location + internal partial interface IProxyResourceInternal : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal + { + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/ProxyResource.json.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/ProxyResource.json.cs new file mode 100644 index 000000000000..8af286b4d4b8 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/ProxyResource.json.cs @@ -0,0 +1,110 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// + /// The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location + /// + public partial class ProxyResource + { + + /// + /// 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.DataBoundary.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization 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.DataBoundary.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.DataBoundary.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.DataBoundary.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IProxyResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IProxyResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IProxyResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json ? new ProxyResource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject instance to deserialize from. + internal ProxyResource(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.Resource(json); + 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.DataBoundary.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __resource?.ToJson(container, serializationMode); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/Resource.PowerShell.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/Resource.PowerShell.cs new file mode 100644 index 000000000000..b93a3f761ef5 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/Resource.PowerShell.cs @@ -0,0 +1,238 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + [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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, 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.DataBoundary.Models.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.DataBoundary.Models.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.DataBoundary.Models.IResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + 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 + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + 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.DataBoundary.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Common fields that are returned in the response for all Azure Resource Manager resources + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial interface IResource + + { + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/Resource.TypeConverter.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/Resource.TypeConverter.cs new file mode 100644 index 000000000000..2f8be02d2987 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/Resource.TypeConverter.cs @@ -0,0 +1,146 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 type. + /// + /// 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.DataBoundary.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 into an instance of + /// + /// 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.DataBoundary.Models.IResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.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/Resources/DataBoundary.Autorest/generated/api/Models/Resource.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/Resource.cs new file mode 100644 index 000000000000..fb5e870e4ca0 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/Resource.cs @@ -0,0 +1,239 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + public partial class Resource : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResource, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal + { + + /// Backing field for property. + private string _id; + + /// + /// Fully qualified resource ID for the resource. E.g. "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}" + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal.SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.SystemData()); set { {_systemData = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResourceInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData _systemData; + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.SystemData()); } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)SystemData).CreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)SystemData).CreatedAt = value ?? default(global::System.DateTime); } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inlined)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)SystemData).CreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)SystemData).CreatedBy = value ?? null; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inlined)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)SystemData).CreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)SystemData).CreatedByType = value ?? null; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)SystemData).LastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)SystemData).LastModifiedAt = value ?? default(global::System.DateTime); } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)SystemData).LastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)SystemData).LastModifiedBy = value ?? null; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)SystemData).LastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)SystemData).LastModifiedByType = value ?? null; } + + /// Backing field for property. + private string _type; + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public Resource() + { + + } + } + /// Common fields that are returned in the response for all Azure Resource Manager resources + public partial interface IResource : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IJsonSerializable + { + /// + /// Fully qualified resource ID for the resource. E.g. "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}" + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Fully qualified resource ID for the resource. E.g. ""/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}""", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the resource", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The timestamp of resource creation (UTC).", + SerializedName = @"createdAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? SystemDataCreatedAt { get; } + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The identity that created the resource.", + SerializedName = @"createdBy", + PossibleTypes = new [] { typeof(string) })] + string SystemDataCreatedBy { get; } + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The type of identity that created the resource.", + SerializedName = @"createdByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataCreatedByType { get; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The timestamp of resource last modification (UTC)", + SerializedName = @"lastModifiedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? SystemDataLastModifiedAt { get; } + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The identity that last modified the resource.", + SerializedName = @"lastModifiedBy", + PossibleTypes = new [] { typeof(string) })] + string SystemDataLastModifiedBy { get; } + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The type of identity that last modified the resource.", + SerializedName = @"lastModifiedByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataLastModifiedByType { get; } + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The type of the resource. E.g. ""Microsoft.Compute/virtualMachines"" or ""Microsoft.Storage/storageAccounts""", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// Common fields that are returned in the response for all Azure Resource Manager resources + internal partial interface IResourceInternal + + { + /// + /// Fully qualified resource ID for the resource. E.g. "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}" + /// + string Id { get; set; } + /// The name of the resource + string Name { get; set; } + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData SystemData { get; set; } + /// The timestamp of resource creation (UTC). + global::System.DateTime? SystemDataCreatedAt { get; set; } + /// The identity that created the resource. + string SystemDataCreatedBy { get; set; } + /// The type of identity that created the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataCreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + global::System.DateTime? SystemDataLastModifiedAt { get; set; } + /// The identity that last modified the resource. + string SystemDataLastModifiedBy { get; set; } + /// The type of identity that last modified the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataLastModifiedByType { get; set; } + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/Resource.json.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/Resource.json.cs new file mode 100644 index 000000000000..97d0df42f487 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/Resource.json.cs @@ -0,0 +1,128 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + 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.DataBoundary.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization 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.DataBoundary.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.DataBoundary.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.DataBoundary.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json ? new Resource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject instance to deserialize from. + internal Resource(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_systemData = If( json?.PropertyT("systemData"), out var __jsonSystemData) ? Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.SystemData.FromJson(__jsonSystemData) : _systemData;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + {_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); + } + + /// + /// 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.DataBoundary.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._systemData ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) this._systemData.ToJson(null,serializationMode) : null, "systemData" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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/Resources/DataBoundary.Autorest/generated/api/Models/SystemData.PowerShell.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/SystemData.PowerShell.cs new file mode 100644 index 000000000000..76c992f3d369 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/SystemData.PowerShell.cs @@ -0,0 +1,204 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// Metadata pertaining to creation and last modification of the resource. + [System.ComponentModel.TypeConverter(typeof(SystemDataTypeConverter))] + public partial class SystemData + { + + /// + /// 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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, 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.DataBoundary.Models.ISystemData DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SystemData(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.DataBoundary.Models.ISystemData DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SystemData(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.DataBoundary.Models.ISystemData FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SystemData(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).CreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).LastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal SystemData(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).CreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal)this).LastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + 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.DataBoundary.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Metadata pertaining to creation and last modification of the resource. + [System.ComponentModel.TypeConverter(typeof(SystemDataTypeConverter))] + public partial interface ISystemData + + { + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/SystemData.TypeConverter.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/SystemData.TypeConverter.cs new file mode 100644 index 000000000000..0b4ac0b3ab9f --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/SystemData.TypeConverter.cs @@ -0,0 +1,146 @@ +// 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.DataBoundary.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SystemDataTypeConverter : 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 type. + /// + /// 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.DataBoundary.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 into an instance of + /// + /// 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.DataBoundary.Models.ISystemData ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SystemData.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SystemData.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SystemData.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/Resources/DataBoundary.Autorest/generated/api/Models/SystemData.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/SystemData.cs new file mode 100644 index 000000000000..7a5aea8f2e36 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/SystemData.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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// Metadata pertaining to creation and last modification of the resource. + public partial class SystemData : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemDataInternal + { + + /// Backing field for property. + private global::System.DateTime? _createdAt; + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public global::System.DateTime? CreatedAt { get => this._createdAt; set => this._createdAt = value; } + + /// Backing field for property. + private string _createdBy; + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string CreatedBy { get => this._createdBy; set => this._createdBy = value; } + + /// Backing field for property. + private string _createdByType; + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string CreatedByType { get => this._createdByType; set => this._createdByType = value; } + + /// Backing field for property. + private global::System.DateTime? _lastModifiedAt; + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public global::System.DateTime? LastModifiedAt { get => this._lastModifiedAt; set => this._lastModifiedAt = value; } + + /// Backing field for property. + private string _lastModifiedBy; + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string LastModifiedBy { get => this._lastModifiedBy; set => this._lastModifiedBy = value; } + + /// Backing field for property. + private string _lastModifiedByType; + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PropertyOrigin.Owned)] + public string LastModifiedByType { get => this._lastModifiedByType; set => this._lastModifiedByType = value; } + + /// Creates an new instance. + public SystemData() + { + + } + } + /// Metadata pertaining to creation and last modification of the resource. + public partial interface ISystemData : + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IJsonSerializable + { + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The timestamp of resource creation (UTC).", + SerializedName = @"createdAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? CreatedAt { get; set; } + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The identity that created the resource.", + SerializedName = @"createdBy", + PossibleTypes = new [] { typeof(string) })] + string CreatedBy { get; set; } + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The type of identity that created the resource.", + SerializedName = @"createdByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string CreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The timestamp of resource last modification (UTC)", + SerializedName = @"lastModifiedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastModifiedAt { get; set; } + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The identity that last modified the resource.", + SerializedName = @"lastModifiedBy", + PossibleTypes = new [] { typeof(string) })] + string LastModifiedBy { get; set; } + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The type of identity that last modified the resource.", + SerializedName = @"lastModifiedByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string LastModifiedByType { get; set; } + + } + /// Metadata pertaining to creation and last modification of the resource. + internal partial interface ISystemDataInternal + + { + /// The timestamp of resource creation (UTC). + global::System.DateTime? CreatedAt { get; set; } + /// The identity that created the resource. + string CreatedBy { get; set; } + /// The type of identity that created the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string CreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + global::System.DateTime? LastModifiedAt { get; set; } + /// The identity that last modified the resource. + string LastModifiedBy { get; set; } + /// The type of identity that last modified the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string LastModifiedByType { get; set; } + + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/api/Models/SystemData.json.cs b/src/Resources/DataBoundary.Autorest/generated/api/Models/SystemData.json.cs new file mode 100644 index 000000000000..27e1a217c7ef --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/api/Models/SystemData.json.cs @@ -0,0 +1,118 @@ +// 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.DataBoundary.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + + /// Metadata pertaining to creation and last modification of the resource. + public partial class SystemData + { + + /// + /// 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.DataBoundary.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization 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.DataBoundary.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.DataBoundary.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.DataBoundary.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.ISystemData FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json ? new SystemData(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject instance to deserialize from. + internal SystemData(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_createdBy = If( json?.PropertyT("createdBy"), out var __jsonCreatedBy) ? (string)__jsonCreatedBy : (string)_createdBy;} + {_createdByType = If( json?.PropertyT("createdByType"), out var __jsonCreatedByType) ? (string)__jsonCreatedByType : (string)_createdByType;} + {_createdAt = If( json?.PropertyT("createdAt"), out var __jsonCreatedAt) ? global::System.DateTime.TryParse((string)__jsonCreatedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonCreatedAtValue) ? __jsonCreatedAtValue : _createdAt : _createdAt;} + {_lastModifiedBy = If( json?.PropertyT("lastModifiedBy"), out var __jsonLastModifiedBy) ? (string)__jsonLastModifiedBy : (string)_lastModifiedBy;} + {_lastModifiedByType = If( json?.PropertyT("lastModifiedByType"), out var __jsonLastModifiedByType) ? (string)__jsonLastModifiedByType : (string)_lastModifiedByType;} + {_lastModifiedAt = If( json?.PropertyT("lastModifiedAt"), out var __jsonLastModifiedAt) ? global::System.DateTime.TryParse((string)__jsonLastModifiedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastModifiedAtValue) ? __jsonLastModifiedAtValue : _lastModifiedAt : _lastModifiedAt;} + 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.DataBoundary.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._createdBy)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._createdBy.ToString()) : null, "createdBy" ,container.Add ); + AddIf( null != (((object)this._createdByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._createdByType.ToString()) : null, "createdByType" ,container.Add ); + AddIf( null != this._createdAt ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._createdAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "createdAt" ,container.Add ); + AddIf( null != (((object)this._lastModifiedBy)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._lastModifiedBy.ToString()) : null, "lastModifiedBy" ,container.Add ); + AddIf( null != (((object)this._lastModifiedByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._lastModifiedByType.ToString()) : null, "lastModifiedByType" ,container.Add ); + AddIf( null != this._lastModifiedAt ? (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonString(this._lastModifiedAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastModifiedAt" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/cmdlets/GetAzDataBoundaryOperation_List.cs b/src/Resources/DataBoundary.Autorest/generated/cmdlets/GetAzDataBoundaryOperation_List.cs new file mode 100644 index 000000000000..7d26d034b905 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/cmdlets/GetAzDataBoundaryOperation_List.cs @@ -0,0 +1,485 @@ +// 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.DataBoundary.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Cmdlets; + using System; + + /// Lists all of the available Microsoft.Resources REST API operations. + /// + /// [OpenAPI] List=>GET:"/providers/Microsoft.Resources/operations" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDataBoundaryOperation_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperation))] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Description(@"Lists all of the available Microsoft.Resources REST API operations.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.HttpPath(Path = "/providers/Microsoft.Resources/operations", ApiVersion = "2024-08-01")] + public partial class GetAzDataBoundaryOperation_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IContext + { + /// 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(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.DataBoundary Client => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// 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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResult + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzDataBoundaryOperation_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.DataBoundary.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.DataBoundary.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsList(onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse + /// 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.DataBoundary.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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperationListResult + /// 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.DataBoundary.Models.IOperationListResult + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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/Resources/DataBoundary.Autorest/generated/cmdlets/GetAzDataBoundaryScope_Get.cs b/src/Resources/DataBoundary.Autorest/generated/cmdlets/GetAzDataBoundaryScope_Get.cs new file mode 100644 index 000000000000..705c98969a36 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/cmdlets/GetAzDataBoundaryScope_Get.cs @@ -0,0 +1,471 @@ +// 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.DataBoundary.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Cmdlets; + using System; + + /// Get data boundary at specified scope + /// + /// [OpenAPI] GetScope=>GET:"/{scope}/providers/Microsoft.Resources/dataBoundaries/{default}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDataBoundaryScope_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition))] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Description(@"Get data boundary at specified scope")] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.HttpPath(Path = "/{scope}/providers/Microsoft.Resources/dataBoundaries/{default}", ApiVersion = "2024-08-01")] + public partial class GetAzDataBoundaryScope_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IContext + { + /// 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(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.DataBoundary Client => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// 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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _scope; + + /// The scope at which the operation is performed. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The scope at which the operation is performed.")] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The scope at which the operation is performed.", + SerializedName = @"scope", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Path)] + public string Scope { get => this._scope; set => this._scope = 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzDataBoundaryScope_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.DataBoundary.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.DataBoundary.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.DataBoundariesGetScope(Scope, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Scope=Scope}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse + /// 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.DataBoundary.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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// 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.DataBoundary.Models.IDataBoundaryDefinition + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/cmdlets/GetAzDataBoundaryTenant_Get.cs b/src/Resources/DataBoundary.Autorest/generated/cmdlets/GetAzDataBoundaryTenant_Get.cs new file mode 100644 index 000000000000..420cb1e45475 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/cmdlets/GetAzDataBoundaryTenant_Get.cs @@ -0,0 +1,457 @@ +// 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.DataBoundary.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Cmdlets; + using System; + + /// Get data boundary of tenant. + /// + /// [OpenAPI] GetTenant=>GET:"/providers/Microsoft.Resources/dataBoundaries/{default}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDataBoundaryTenant_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition))] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Description(@"Get data boundary of tenant.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.HttpPath(Path = "/providers/Microsoft.Resources/dataBoundaries/{default}", ApiVersion = "2024-08-01")] + public partial class GetAzDataBoundaryTenant_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IContext + { + /// 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(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.DataBoundary Client => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// 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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzDataBoundaryTenant_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.DataBoundary.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.DataBoundary.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.DataBoundariesGetTenant(onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse + /// 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.DataBoundary.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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// 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.DataBoundary.Models.IDataBoundaryDefinition + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/cmdlets/SetAzDataBoundary_Put.cs b/src/Resources/DataBoundary.Autorest/generated/cmdlets/SetAzDataBoundary_Put.cs new file mode 100644 index 000000000000..6b18fe630eba --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/cmdlets/SetAzDataBoundary_Put.cs @@ -0,0 +1,528 @@ +// 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.DataBoundary.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Cmdlets; + using System; + + /// Opt-in tenant to data boundary. + /// + /// [OpenAPI] Put=>PUT:"/providers/Microsoft.Resources/dataBoundaries/{default}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzDataBoundary_Put", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition))] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Description(@"Opt-in tenant to data boundary.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.HttpPath(Path = "/providers/Microsoft.Resources/dataBoundaries/{default}", ApiVersion = "2024-08-01")] + public partial class SetAzDataBoundary_Put : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IContext + { + /// 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(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.DataBoundary Client => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.ClientAPI; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition _dataBoundaryDefinition; + + /// A data boundary definition. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "A data boundary definition.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"A data boundary definition.", + SerializedName = @"dataBoundaryDefinition", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition DataBoundaryDefinition { get => this._dataBoundaryDefinition; set => this._dataBoundaryDefinition = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// 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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnCreated will be called before the regular onCreated 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// 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.DataBoundary.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.DataBoundary.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'DataBoundariesPut' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.DataBoundariesPut(DataBoundaryDefinition, onOk, onCreated, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzDataBoundary_Put() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnCreated(responseMessage, response, ref _returnNow); + // if overrideOnCreated has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onCreated - response for 201 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse + /// 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.DataBoundary.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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// 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.DataBoundary.Models.IDataBoundaryDefinition + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/cmdlets/SetAzDataBoundary_PutExpanded.cs b/src/Resources/DataBoundary.Autorest/generated/cmdlets/SetAzDataBoundary_PutExpanded.cs new file mode 100644 index 000000000000..57377ad47cdb --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/cmdlets/SetAzDataBoundary_PutExpanded.cs @@ -0,0 +1,529 @@ +// 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.DataBoundary.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Cmdlets; + using System; + + /// Opt-in tenant to data boundary. + /// + /// [OpenAPI] Put=>PUT:"/providers/Microsoft.Resources/dataBoundaries/{default}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzDataBoundary_PutExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition))] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Description(@"Opt-in tenant to data boundary.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.HttpPath(Path = "/providers/Microsoft.Resources/dataBoundaries/{default}", ApiVersion = "2024-08-01")] + public partial class SetAzDataBoundary_PutExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IContext + { + /// 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(); + + /// A data boundary definition. + private Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition _dataBoundaryDefinitionBody = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.DataBoundaryDefinition(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.DataBoundary Client => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.ClientAPI; + + /// The data boundary definition. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The data boundary definition.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The data boundary definition.", + SerializedName = @"dataBoundary", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.PSArgumentCompleterAttribute("NotDefined", "Global", "EU")] + public string DataBoundary { get => _dataBoundaryDefinitionBody.DataBoundary ?? null; set => _dataBoundaryDefinitionBody.DataBoundary = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// 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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnCreated will be called before the regular onCreated 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// 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.DataBoundary.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.DataBoundary.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'DataBoundariesPut' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.DataBoundariesPut(_dataBoundaryDefinitionBody, onOk, onCreated, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzDataBoundary_PutExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnCreated(responseMessage, response, ref _returnNow); + // if overrideOnCreated has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onCreated - response for 201 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse + /// 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.DataBoundary.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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// 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.DataBoundary.Models.IDataBoundaryDefinition + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/cmdlets/SetAzDataBoundary_PutViaJsonFilePath.cs b/src/Resources/DataBoundary.Autorest/generated/cmdlets/SetAzDataBoundary_PutViaJsonFilePath.cs new file mode 100644 index 000000000000..1ca5014a6c08 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/cmdlets/SetAzDataBoundary_PutViaJsonFilePath.cs @@ -0,0 +1,530 @@ +// 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.DataBoundary.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Cmdlets; + using System; + + /// Opt-in tenant to data boundary. + /// + /// [OpenAPI] Put=>PUT:"/providers/Microsoft.Resources/dataBoundaries/{default}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzDataBoundary_PutViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition))] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Description(@"Opt-in tenant to data boundary.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.HttpPath(Path = "/providers/Microsoft.Resources/dataBoundaries/{default}", ApiVersion = "2024-08-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.NotSuggestDefaultParameterSet] + public partial class SetAzDataBoundary_PutViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IContext + { + /// 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(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + public global::System.String _jsonString; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.DataBoundary Client => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// 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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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; } } + + /// Backing field for property. + private string _jsonFilePath; + + /// Path of Json file supplied to the Put operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Put operation")] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Put operation", + SerializedName = @"JsonFilePath", + PossibleTypes = new [] { typeof(string) })] + public string JsonFilePath { get => this._jsonFilePath; set { if (!System.IO.File.Exists(value)) { throw new Exception("Cannot find File " + value); } this._jsonString = System.IO.File.ReadAllText(value); this._jsonFilePath = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnCreated will be called before the regular onCreated 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// 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.DataBoundary.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.DataBoundary.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'DataBoundariesPut' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.DataBoundariesPutViaJsonString(_jsonString, onOk, onCreated, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzDataBoundary_PutViaJsonFilePath() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnCreated(responseMessage, response, ref _returnNow); + // if overrideOnCreated has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onCreated - response for 201 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse + /// 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.DataBoundary.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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// 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.DataBoundary.Models.IDataBoundaryDefinition + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/cmdlets/SetAzDataBoundary_PutViaJsonString.cs b/src/Resources/DataBoundary.Autorest/generated/cmdlets/SetAzDataBoundary_PutViaJsonString.cs new file mode 100644 index 000000000000..e6e4ee106949 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/cmdlets/SetAzDataBoundary_PutViaJsonString.cs @@ -0,0 +1,528 @@ +// 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.DataBoundary.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Cmdlets; + using System; + + /// Opt-in tenant to data boundary. + /// + /// [OpenAPI] Put=>PUT:"/providers/Microsoft.Resources/dataBoundaries/{default}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzDataBoundary_PutViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition))] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Description(@"Opt-in tenant to data boundary.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.HttpPath(Path = "/providers/Microsoft.Resources/dataBoundaries/{default}", ApiVersion = "2024-08-01")] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.NotSuggestDefaultParameterSet] + public partial class SetAzDataBoundary_PutViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IContext + { + /// 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(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.DataBoundary Client => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// 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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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; } } + + /// Backing field for property. + private string _jsonString; + + /// Json string supplied to the Put operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Put operation")] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Put operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnCreated will be called before the regular onCreated 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// 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.DataBoundary.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.DataBoundary.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'DataBoundariesPut' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.DataBoundariesPutViaJsonString(_jsonString, onOk, onCreated, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzDataBoundary_PutViaJsonString() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnCreated(responseMessage, response, ref _returnNow); + // if overrideOnCreated has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onCreated - response for 201 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// 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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IErrorResponse + /// 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.DataBoundary.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 Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + /// 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.DataBoundary.Models.IDataBoundaryDefinition + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/AsyncCommandRuntime.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/AsyncCommandRuntime.cs new file mode 100644 index 000000000000..97111fee71fc --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/AsyncCommandRuntime.cs @@ -0,0 +1,832 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.Runtime.PowerShell +{ + using System.Management.Automation; + using System.Management.Automation.Host; + using System.Threading; + using System.Linq; + + internal interface IAsyncCommandRuntimeExtensions + { + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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; + if (cmdlet.PagingParameters != null) + { + WriteDebug("Client side pagination is enabled for this 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.DataBoundary.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/AsyncJob.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/AsyncJob.cs new file mode 100644 index 000000000000..8ca2c1c59db4 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/AsyncOperationResponse.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/AsyncOperationResponse.cs new file mode 100644 index 000000000000..b0beda6b51a9 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/AsyncOperationResponse.cs @@ -0,0 +1,176 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.Runtime.PowerShell +{ + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.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.DataBoundary.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.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 a type + /// 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.DataBoundary.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 into an instance of + /// + /// 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/Resources/DataBoundary.Autorest/generated/runtime/Attributes/ExternalDocsAttribute.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Attributes/ExternalDocsAttribute.cs new file mode 100644 index 000000000000..70b04cd65ec5 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/Attributes/ExternalDocsAttribute.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. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary +{ + using System; + using System.Collections.Generic; + using System.Text; + + [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] + public class ExternalDocsAttribute : Attribute + { + + public string Description { get; } + + public string Url { get; } + + public ExternalDocsAttribute(string url) + { + Url = url; + } + + public ExternalDocsAttribute(string url, string description) + { + Url = url; + Description = description; + } + } +} diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs new file mode 100644 index 000000000000..c16e14e6b857 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs @@ -0,0 +1,52 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary +{ + public class PSArgumentCompleterAttribute : ArgumentCompleterAttribute + { + internal string[] ResourceTypes; + + public PSArgumentCompleterAttribute(params string[] argumentList) : base(CreateScriptBlock(argumentList)) + { + ResourceTypes = argumentList; + } + + public static ScriptBlock CreateScriptBlock(string[] resourceTypes) + { + List outputResourceTypes = new List(); + foreach (string resourceType in resourceTypes) + { + if (resourceType.Contains(" ")) + { + outputResourceTypes.Add("\'\'" + resourceType + "\'\'"); + } + else + { + outputResourceTypes.Add(resourceType); + } + } + string scriptResourceTypeList = "'" + String.Join("' , '", outputResourceTypes) + "'"; + string script = "param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)\n" + + String.Format("$values = {0}\n", scriptResourceTypeList) + + "$values | Where-Object { $_ -Like \"$wordToComplete*\" -or $_ -Like \"'$wordToComplete*\" } | Sort-Object | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }"; + ScriptBlock scriptBlock = ScriptBlock.Create(script); + return scriptBlock; + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs new file mode 100644 index 000000000000..322cacc95d1e --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs new file mode 100644 index 000000000000..8fe913e2251b --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs new file mode 100644 index 000000000000..b3d09cd19603 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs @@ -0,0 +1,103 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.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.DataBoundary.Models"; + private const string SupportNamespace = @"${$project.supportNamespace.fullName}"; + private const string PropertiesExcludedForTableview = @"Id,Type"; + + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + private static string SelectedBySuffix = @"#Multiple"; + + 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() + && (!PropertiesExcludedForTableview.Split(',').Contains(pf.Property.Name)) + && (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 = string.Concat(viewParameters.Type.FullName, SelectedBySuffix) + }, + 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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs new file mode 100644 index 000000000000..f9e66f5a953a --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs @@ -0,0 +1,56 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.Runtime.PowerShell.MarkdownRenderer; + +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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; } + + [Parameter()] + public SwitchParameter AddComplexInterfaceInfo { 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, AddComplexInterfaceInfo.IsPresent); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs new file mode 100644 index 000000000000..24f86ac39537 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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.DataBoundary.Models"; + private const string SupportNamespace = @"${$project.supportNamespace.fullName}"; + + 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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs new file mode 100644 index 000000000000..61a8fe0bea7b --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.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.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.PsHelpers; +using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.MarkdownRenderer; +using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.PsProxyTypeExtensions; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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)] + [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; } + + [Parameter(ParameterSetName = "Docs")] + public SwitchParameter AddComplexInterfaceInfo { 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(); + var license = new StringBuilder(); + license.Append(@" +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +"); + HashSet LicenseSet = new HashSet(); + 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($"{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; + parameters = parameters.Where(p => !p.IsHidden()); + if (!parameters.Any()) + { + continue; + } + 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.HasAllowEmptyArray.ToAllowEmptyArray()); + 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, license.ToString()); + File.AppendAllText(variantGroup.FilePath, sb.ToString()); + if (!LicenseSet.Contains(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"))) + { + // only add license in the header + File.AppendAllText(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"), license.ToString()); + LicenseSet.Add(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1")); + } + 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, AddComplexInterfaceInfo.IsPresent); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs new file mode 100644 index 000000000000..df7e643ff56b --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs @@ -0,0 +1,193 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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; + private const string Undefined = "undefined"; + private bool IsUndefined(string value) => string.Equals(Undefined, value, StringComparison.OrdinalIgnoreCase); + + 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.1"); + // 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.DataBoundary.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: DataBoundary cmdlets"}'"); + sb.AppendLine($@"{Indent}PowerShellVersion = '5.1'"); + sb.AppendLine($@"{Indent}DotNetFrameworkVersion = '4.7.2'"); + + // RequiredModules + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}RequiredModules = @({"undefined"})"); + } + + // RequiredAssemblies + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}RequiredAssemblies = @({"undefined"})"); + } + else + { + sb.AppendLine($@"{Indent}RequiredAssemblies = '{"./bin/Az.DataBoundary.private.dll"}'"); + } + + // NestedModules + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}NestedModules = @({"undefined"})"); + } + + // FormatsToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}FormatsToProcess = @({"undefined"})"); + } + else + { + var customFormatPs1xmlFiles = Directory.GetFiles(CustomFolder) + .Where(f => f.EndsWith(".format.ps1xml")) + .Select(f => $"{CustomFolderRelative}/{Path.GetFileName(f)}"); + var formatList = customFormatPs1xmlFiles.Prepend("./Az.DataBoundary.format.ps1xml").ToPsList(); + sb.AppendLine($@"{Indent}FormatsToProcess = {formatList}"); + } + + // TypesToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}TypesToProcess = @({"undefined"})"); + } + + // ScriptsToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}ScriptsToProcess = @({"undefined"})"); + } + + var functionInfos = GetScriptCmdlets(ExportsFolder).ToArray(); + // FunctionsToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}FunctionsToExport = @({"undefined"})"); + } + else + { + var cmdletsList = functionInfos.Select(fi => fi.Name).Distinct().ToPsList(); + sb.AppendLine($@"{Indent}FunctionsToExport = {cmdletsList}"); + } + + // AliasesToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}AliasesToExport = @({"undefined"})"); + } + else + { + var aliasesList = functionInfos.SelectMany(fi => fi.ScriptBlock.Attributes).ToAliasNames().ToPsList(); + if (!String.IsNullOrEmpty(aliasesList)) { + sb.AppendLine($@"{Indent}AliasesToExport = {aliasesList}"); + } + } + + // CmdletsToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}CmdletsToExport = @({"undefined"})"); + } + + 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 DataBoundary".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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs new file mode 100644 index 000000000000..7b81027eec19 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs @@ -0,0 +1,197 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 loadEnvFile = Path.Combine(OutputFolder, "loadEnv.ps1"); + if (!File.Exists(loadEnvFile)) + { + var sc = new StringBuilder(); + sc.AppendLine(@" +$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 +}"); + File.WriteAllText(loadEnvFile, sc.ToString()); + }*/ + 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]$_}) + } +} +function Start-TestSleep { + [CmdletBinding(DefaultParameterSetName = 'SleepBySeconds')] + param( + [parameter(Mandatory = $true, Position = 0, ParameterSetName = 'SleepBySeconds')] + [ValidateRange(0.0, 2147483.0)] + [double] $Seconds, + + [parameter(Mandatory = $true, ParameterSetName = 'SleepByMilliseconds')] + [ValidateRange('NonNegative')] + [Alias('ms')] + [int] $Milliseconds + ) + + if ($TestMode -ne 'playback') { + switch ($PSCmdlet.ParameterSetName) { + 'SleepBySeconds' { + Start-Sleep -Seconds $Seconds + } + 'SleepByMilliseconds' { + Start-Sleep -Milliseconds $Milliseconds + } + } + } +} + +$env = @{} +if ($UsePreviousConfigForRecord) { + $previousEnv = Get-Content (Join-Path $PSScriptRoot 'env.json') | ConvertFrom-Json + $previousEnv.psobject.properties | Foreach-Object { $env[$_.Name] = $_.Value } +} +# Add script method called AddWithCache to $env, when useCache is set true, it will try to get the value from the $env first. +# example: $val = $env.AddWithCache('key', $val, $true) +$env | Add-Member -Type ScriptMethod -Value { param( [string]$key, [object]$val, [bool]$useCache) if ($this.Contains($key) -and $useCache) { return $this[$key] } else { $this[$key] = $val; return $val } } -Name 'AddWithCache' +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($"if(($null -eq $TestName) -or ($TestName -contains '{variantGroup.CmdletName}'))"); + 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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs new file mode 100644 index 000000000000..7a4eb7314585 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs new file mode 100644 index 000000000000..9bdd6ce5ab02 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs new file mode 100644 index 000000000000..3d51b3f03b2c --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs @@ -0,0 +1,54 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.Error.WriteLine($"{ee.GetType().Name}: {ee.Message}"); + System.Console.Error.WriteLine(ee.StackTrace); + throw ee; + } + } + } +} diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/CollectionExtensions.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/CollectionExtensions.cs new file mode 100644 index 000000000000..1cc89d258229 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/MarkdownRenderer.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/MarkdownRenderer.cs new file mode 100644 index 000000000000..861c41a0c1a1 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/MarkdownRenderer.cs @@ -0,0 +1,122 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.PsProxyOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell +{ + internal static class MarkdownRenderer + { + public static void WriteMarkdowns(IEnumerable variantGroups, PsModuleHelpInfo moduleHelpInfo, string docsFolder, string examplesFolder, bool AddComplexInterfaceInfo = true) + { + 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()); + } + } + + 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}"); + if (markdownInfo.Aliases.Any()) + { + sb.Append($"ALIASES{Environment.NewLine}{Environment.NewLine}"); + } + foreach (var alias in markdownInfo.Aliases) + { + sb.Append($"{alias}{Environment.NewLine}{Environment.NewLine}"); + } + + if (AddComplexInterfaceInfo) + { + 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}]({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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Models/PsFormatTypes.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Models/PsFormatTypes.cs new file mode 100644 index 000000000000..5aedd3fa0582 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs new file mode 100644 index 000000000000..e1232b42f863 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.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.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 + { + private string ExampleTemplate = + "{0}{1}" + Environment.NewLine + + "{2}" + Environment.NewLine + "{3}" + Environment.NewLine + "{4}" + Environment.NewLine + Environment.NewLine + + "{5}" + Environment.NewLine + Environment.NewLine; + + private string ExampleTemplateWithOutput = + "{0}{1}" + Environment.NewLine + + "{2}" + Environment.NewLine + "{3}" + Environment.NewLine + "{4}" + Environment.NewLine + Environment.NewLine + + "{5}" + Environment.NewLine + "{6}" + Environment.NewLine + "{7}" + Environment.NewLine + Environment.NewLine + + "{8}" + Environment.NewLine + Environment.NewLine; + + public MarkdownExampleHelpInfo ExampleInfo { get; } + + public HelpExampleOutput(MarkdownExampleHelpInfo exampleInfo) + { + ExampleInfo = exampleInfo; + } + + public override string ToString() + { + if (string.IsNullOrEmpty(ExampleInfo.Output)) + { + return string.Format(ExampleTemplate, + ExampleNameHeader, ExampleInfo.Name, + ExampleCodeHeader, ExampleInfo.Code, ExampleCodeFooter, + ExampleInfo.Description.ToDescriptionFormat()); + } + else + { + return string.Format(ExampleTemplateWithOutput, + ExampleNameHeader, ExampleInfo.Name, + ExampleCodeHeader, ExampleInfo.Code, ExampleCodeFooter, + ExampleOutputHeader, ExampleInfo.Output, ExampleOutputFooter, + 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://learn.microsoft.com/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.Synopsis.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 const string ExampleOutputHeader = "```output"; + public const string ExampleOutputFooter = "```"; + + 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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Models/PsHelpTypes.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Models/PsHelpTypes.cs new file mode 100644 index 000000000000..696384ff2b5c --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Models/PsHelpTypes.cs @@ -0,0 +1,202 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.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 Output { get; } + public string Remarks { get; } + + public PsHelpExampleInfo(PSObject exampleObject) + { + Title = exampleObject.GetProperty("title"); + Code = exampleObject.GetProperty("code"); + Output = exampleObject.GetProperty("output"); + Remarks = exampleObject.GetProperty("remarks").EmptyIfNull().ToDescriptionText(); + } + public PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) + { + Title = markdownExample.Name; + Code = markdownExample.Code; + Output = markdownExample.Output; + 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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs new file mode 100644 index 000000000000..74c8e7d0aa22 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs @@ -0,0 +1,329 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 MarkdownRelatedLinkInfo[] RelatedLinks { get; } + + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public MarkdownHelpInfo(VariantGroup variantGroup, string examplesFolder, string externalHelpFilename = "") + { + ExternalHelpFilename = externalHelpFilename; + ModuleName = variantGroup.RootModuleName != "" ? variantGroup.RootModuleName : 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 && !pg.Parameters.All(p => p.IsHidden())) + .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; + + var relatedLinkLists = new List(); + relatedLinkLists.AddRange(commentInfo.RelatedLinks?.Select(link => new MarkdownRelatedLinkInfo(link))); + relatedLinkLists.AddRange(variantGroup.Variants.SelectMany(v => v.Attributes).OfType()?.Distinct()?.Select(link => new MarkdownRelatedLinkInfo(link.Url, link.Description))); + RelatedLinks = relatedLinkLists?.ToArray(); + + 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 outputStartIndex = eg.Select((l, i) => l.StartsWith(ExampleOutputHeader) ? (int?)i : null).FirstOrDefault(i => i.HasValue); + var outputEndIndex = eg.Select((l, i) => l.StartsWith(ExampleOutputFooter) ? (int?)i : null).FirstOrDefault(i => i.HasValue && i > outputStartIndex); + var output = outputStartIndex.HasValue && outputEndIndex.HasValue + ? String.Join(Environment.NewLine, eg.Skip(outputStartIndex.Value + 1).Take(outputEndIndex.Value - (outputStartIndex.Value + 1))) + : String.Empty; + var descriptionStartIndex = (outputEndIndex ?? (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, output, 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 && !p.IsHidden()).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]"); + } + 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 Output { get; } + public string Description { get; } + + public MarkdownExampleHelpInfo(string name, string code, string output, string description) + { + Name = name; + Code = code; + Output = output; + 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 class MarkdownRelatedLinkInfo + { + public string Url { get; } + public string Description { get; } + + public MarkdownRelatedLinkInfo(string url) + { + Url = url; + } + + public MarkdownRelatedLinkInfo(string url, string description) + { + Url = url; + Description = description; + } + + public override string ToString() + { + if (string.IsNullOrEmpty(Description)) + { + return Url; + } + else + { + return $@"[{Description}]({Url})"; + + } + + } + } + + internal static class MarkdownTypesExtensions + { + public static MarkdownExampleHelpInfo ToExampleHelpInfo(this PsHelpExampleInfo exampleInfo) => new MarkdownExampleHelpInfo(exampleInfo.Title, exampleInfo.Code, exampleInfo.Output, exampleInfo.Remarks); + + public static MarkdownExampleHelpInfo[] DefaultExampleHelpInfos = + { + new MarkdownExampleHelpInfo("Example 1: {{ Add title here }}", $@"{{{{ Add code here }}}}", $@"{{{{ Add output here (remove the output block if the example doesn't have an output) }}}}", @"{{ Add description here }}"), + new MarkdownExampleHelpInfo("Example 2: {{ Add title here }}", $@"{{{{ Add code here }}}}", $@"{{{{ Add output here (remove the output block if the example doesn't have an output) }}}}", @"{{ 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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Models/PsProxyOutputs.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Models/PsProxyOutputs.cs new file mode 100644 index 000000000000..0443a1b680e1 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Models/PsProxyOutputs.cs @@ -0,0 +1,662 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 AllowEmptyArrayOutput + { + public bool HasAllowEmptyArray { get; } + + public AllowEmptyArrayOutput(bool hasAllowEmptyArray) + { + HasAllowEmptyArray = hasAllowEmptyArray; + } + + public override string ToString() => HasAllowEmptyArray ? $"{Indent}[AllowEmptyCollection()]{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 PSArgumentCompleterOutput : ArgumentCompleterOutput + { + public PSArgumentCompleterInfo PSArgumentCompleterInfo { get; } + + public PSArgumentCompleterOutput(PSArgumentCompleterInfo completerInfo) : base(completerInfo) + { + PSArgumentCompleterInfo = completerInfo; + } + + + public override string ToString() => PSArgumentCompleterInfo != null + ? $"{Indent}[{typeof(PSArgumentCompleterAttribute)}({(PSArgumentCompleterInfo.IsTypeCompleter ? $"[{PSArgumentCompleterInfo.Type.Unwrap().ToPsType()}]" : $"{PSArgumentCompleterInfo.ResourceTypes?.Select(r => $"\"{r}\"")?.JoinIgnoreEmpty(", ")}")})]{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 BaseOutput + { + public VariantGroup VariantGroup { get; } + + protected static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + public BaseOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + public string ClearTelemetryContext() + { + return (!VariantGroup.IsInternal && IsAzure) ? $@"{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext()" : ""; + } + } + + internal class BeginOutput : BaseOutput + { + public BeginOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + public string GetProcessCustomAttributesAtRuntime() + { + return VariantGroup.IsInternal ? "" : IsAzure ? $@"{Indent}{Indent}$cmdInfo = Get-Command -Name $mapping[$parameterSet] +{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}if ($null -ne $MyInvocation.MyCommand -and [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets -notcontains $MyInvocation.MyCommand.Name -and [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ContainsPreviewAttribute($cmdInfo, $MyInvocation)){{ +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets.Enqueue($MyInvocation.MyCommand.Name) +{Indent}{Indent}}}" : $@"{Indent}{Indent}$cmdInfo = Get-Command -Name $mapping[$parameterSet]{Environment.NewLine}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet)"; + } + + private string GetTelemetry() + { + if (!VariantGroup.IsInternal && IsAzure) + { + return $@" +{Indent}{Indent}if ($null -eq [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion) {{ +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion = $PSVersionTable.PSVersion.ToString() +{Indent}{Indent}}} +{Indent}{Indent}$preTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId +{Indent}{Indent}if ($preTelemetryId -eq '') {{ +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId =(New-Guid).ToString() +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.module]::Instance.Telemetry.Invoke('Create', $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}}} else {{ +{Indent}{Indent}{Indent}$internalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets +{Indent}{Indent}{Indent}if ($internalCalledCmdlets -eq '') {{ +{Indent}{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $MyInvocation.MyCommand.Name +{Indent}{Indent}{Indent}}} else {{ +{Indent}{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets += ',' + $MyInvocation.MyCommand.Name +{Indent}{Indent}{Indent}}} +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = 'internal' +{Indent}{Indent}}} +"; + } + return ""; + } + 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 +{GetTelemetry()} +{GetParameterSetToCmdletMapping()}{GetDefaultValuesStatements()} +{GetProcessCustomAttributesAtRuntime()} +{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 {{ +{ClearTelemetryContext()} +{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(); + var setCondition = " "; + if (!String.IsNullOrEmpty(defaultInfo.SetCondition)) + { + setCondition = $" -and {defaultInfo.SetCondition}"; + } + //Yabo: this is bad to hard code the subscription id, but autorest load input README.md reversely (entry readme -> required readme), there are no other way to + //override default value set in required readme + if ("SubscriptionId".Equals(parameterName)) + { + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}'){setCondition}) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$testPlayback = $false"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['HttpPipelinePrepend'] | Foreach-Object {{ if ($_) {{ $testPlayback = $testPlayback -or ('Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PipelineMock' -eq $_.Target.GetType().FullName -and 'Playback' -eq $_.Target.Mode) }} }}"); + sb.AppendLine($"{Indent}{Indent}{Indent}if ($testPlayback) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = . (Join-Path $PSScriptRoot '..' 'utils' 'Get-SubscriptionIdTestSafe.ps1')"); + sb.AppendLine($"{Indent}{Indent}{Indent}}} else {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.AppendLine($"{Indent}{Indent}{Indent}}}"); + sb.Append($"{Indent}{Indent}}}"); + } + else + { + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}'){setCondition}) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.Append($"{Indent}{Indent}}}"); + } + + } + return sb.ToString(); + } + + } + + internal class ProcessOutput : BaseOutput + { + public ProcessOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + private string GetFinally() + { + if (IsAzure && !VariantGroup.IsInternal) + { + return $@" +{Indent}finally {{ +{Indent}{Indent}$backupTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId +{Indent}{Indent}$backupInternalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() +{Indent}}} +"; + } + return ""; + } + public override string ToString() => $@"process {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.Process($_) +{Indent}}} catch {{ +{ClearTelemetryContext()} +{Indent}{Indent}throw +{Indent}}} +{GetFinally()} +}} +"; + } + + internal class EndOutput : BaseOutput + { + public EndOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + private string GetTelemetry() + { + if (!VariantGroup.IsInternal && IsAzure) + { + return $@" +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $backupTelemetryId +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $backupInternalCalledCmdlets +{Indent}{Indent}if ($preTelemetryId -eq '') {{ +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.module]::Instance.Telemetry.Invoke('Send', $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() +{Indent}{Indent}}} +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $preTelemetryId +"; + } + return ""; + } + public override string ToString() => $@"end {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.End() +{GetTelemetry()} +{Indent}}} catch {{ +{ClearTelemetryContext()} +{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 externalUrls = String.Join(Environment.NewLine, CommentInfo.ExternalUrls.Select(l => $".Link{Environment.NewLine}{l}")); + var externalUrlsText = !String.IsNullOrEmpty(externalUrls) ? $"{Environment.NewLine}{externalUrls}" : 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}{externalUrlsText} +#> +"; + } + } + + 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}{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 AllowEmptyArrayOutput ToAllowEmptyArray(this bool hasAllowEmptyArray) => new AllowEmptyArrayOutput(hasAllowEmptyArray); + + public static ArgumentCompleterOutput ToArgumentCompleterOutput(this CompleterInfo completerInfo) => (completerInfo is PSArgumentCompleterInfo psArgumentCompleterInfo) ? psArgumentCompleterInfo.ToArgumentCompleterOutput() : new ArgumentCompleterOutput(completerInfo); + + public static PSArgumentCompleterOutput ToArgumentCompleterOutput(this PSArgumentCompleterInfo completerInfo) => new PSArgumentCompleterOutput(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(variantGroup); + + public static EndOutput ToEndOutput(this VariantGroup variantGroup) => new EndOutput(variantGroup); + + 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, includeBackticks)); + return String.Join(Environment.NewLine, nested); + } + } +} diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Models/PsProxyTypes.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Models/PsProxyTypes.cs new file mode 100644 index 000000000000..f6bb362f8941 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/Models/PsProxyTypes.cs @@ -0,0 +1,544 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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 RootModuleName { get => @"Az.Resources"; } + 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 + .Where(v => !v.IsNotSuggestDefaultParameterSet) + .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(); + if (variantParamCountGroups.Length == 0) + { + 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 bool IsNotSuggestDefaultParameterSet { 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(); + IsNotSuggestDefaultParameterSet = 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 bool HasAllowEmptyArray { 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(); + HasAllowEmptyArray = Parameters.SelectMany(p => p.Attributes.OfType()).Any(); + CompleterInfo = Parameters.Select(p => p.CompleterInfoAttribute).FirstOrDefault()?.ToCompleterInfo() + ?? Parameters.Select(p => p.PSArgumentCompleterAttribute).FirstOrDefault()?.ToPSArgumentCompleterInfo() + ?? 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 PSArgumentCompleterAttribute PSArgumentCompleterAttribute { 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(); + PSArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(); + ArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(attr => !attr.GetType().Equals(typeof(PSArgumentCompleterAttribute))); + + 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}"; + 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(); + // 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; } + public string[] ExternalUrls { get; } + + private const string HelpLinkPrefix = @"https://learn.microsoft.com/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(); + + // Use root module name in the help link + var moduleName = variantGroup.RootModuleName == "" ? variantGroup.ModuleName.ToLowerInvariant() : variantGroup.RootModuleName.ToLowerInvariant(); + OnlineVersion = helpInfo.OnlineVersion?.Uri.NullIfEmpty() ?? $@"{HelpLinkPrefix}{moduleName}/{variantGroup.CmdletName.ToLowerInvariant()}"; + RelatedLinks = helpInfo.RelatedLinks.Select(rl => rl.Text).ToArray(); + + // Get external urls from attribute + ExternalUrls = variantGroup.Variants.SelectMany(v => v.Attributes).OfType()?.Select(e => e.Url)?.Distinct()?.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 PSArgumentCompleterInfo : CompleterInfo + { + public string[] ResourceTypes { get; } + + public PSArgumentCompleterInfo(PSArgumentCompleterAttribute completerAttribute) : base(completerAttribute) + { + ResourceTypes = completerAttribute.ResourceTypes; + } + } + + internal class DefaultInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public string SetCondition { get; } + public ParameterGroup ParameterGroup { get; } + + public DefaultInfo(DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + SetCondition = infoAttribute.SetCondition; + 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)) && ph.Name != "IncludeTotalCount"); + } + var result = parameters.Select(p => new Parameter(variant.VariantName, p.Key, p.Value, parameterHelp.FirstOrDefault(ph => ph.Name == p.Key))); + if (variant.SupportsPaging) + { + // If supportsPaging is set, we will need to add First and Skip parameters since they are treated as common parameters which as not contained on Metadata>parameters + variant.Info.Parameters["First"].Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == variant.VariantName || pa.ParameterSetName == AllParameterSets).HelpMessage = "Gets only the first 'n' objects."; + variant.Info.Parameters["Skip"].Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == variant.VariantName || pa.ParameterSetName == AllParameterSets).HelpMessage = "Ignores the first 'n' objects and then gets the remaining objects."; + result = result.Append(new Parameter(variant.VariantName, "First", variant.Info.Parameters["First"], parameterHelp.FirstOrDefault(ph => ph.Name == "First"))); + result = result.Append(new Parameter(variant.VariantName, "Skip", variant.Info.Parameters["Skip"], parameterHelp.FirstOrDefault(ph => ph.Name == "Skip"))); + } + return result.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 PSArgumentCompleterInfo ToPSArgumentCompleterInfo(this PSArgumentCompleterAttribute completerAttribute) => new PSArgumentCompleterInfo(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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/PsAttributes.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/PsAttributes.cs new file mode 100644 index 000000000000..e2298b049edf --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/PsAttributes.cs @@ -0,0 +1,131 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary +{ + [AttributeUsage(AttributeTargets.Class)] + public class DescriptionAttribute : Attribute + { + public string Description { get; } + + public DescriptionAttribute(string description) + { + Description = description; + } + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + 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.Class)] + public class HttpPathAttribute : Attribute + { + public string Path { get; set; } + public string ApiVersion { get; set; } + } + + [AttributeUsage(AttributeTargets.Class)] + public class NotSuggestDefaultParameterSetAttribute : Attribute + { + } + + [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 ConstantAttribute : Attribute + { + } + + [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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/PsExtensions.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/PsExtensions.cs new file mode 100644 index 000000000000..b2d63e315325 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/PsExtensions.cs @@ -0,0 +1,176 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.Runtime.PowerShell +{ + internal static class PsExtensions + { + public static PSObject AddMultipleTypeNameIntoPSObject(this object obj, string multipleTag = "#Multiple") + { + var psObj = new PSObject(obj); + psObj.TypeNames.Insert(0, $"{psObj.TypeNames[0]}{multipleTag}"); + return psObj; + } + + // 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()); + + /// + /// Returns if a parameter should be hidden by checking for . + /// + /// A PowerShell parameter. + public static bool IsHidden(this Parameter parameter) + { + return parameter.Attributes.Any(attr => attr is DoNotExportAttribute); + } + } +} diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/PsHelpers.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/PsHelpers.cs new file mode 100644 index 000000000000..dc822a4c57e3 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/PsHelpers.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. + *--------------------------------------------------------------------------------------------*/ +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.DataBoundary.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 wrappedFolder = scriptFolder.Contains("'") ? $@"""{scriptFolder}""" : $@"'{scriptFolder}'"; + var getCmdletsCommand = $@" +$currentFunctions = Get-ChildItem function: +Get-ChildItem -Path {wrappedFolder} -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.TrimStart().StartsWith(GuidStart.TrimStart()))?.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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/StringExtensions.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/StringExtensions.cs new file mode 100644 index 000000000000..34b4b6d61ed0 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/XmlExtensions.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/BuildTime/XmlExtensions.cs new file mode 100644 index 000000000000..726ee401a982 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/CmdInfoHandler.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/CmdInfoHandler.cs new file mode 100644 index 000000000000..c92efeb72c3a --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Context.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Context.cs new file mode 100644 index 000000000000..b16f68e36453 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/Context.cs @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.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.DataBoundary.Runtime.Extensions; + + /// + /// The IContext Interface defines the communication mechanism for input customization. + /// + /// + /// In the context, we will have client, pipeline, PSBoundParamters, default EventListener, Cancellation. + /// + public interface IContext + { + System.Management.Automation.InvocationInfo InvocationInformation { get; set; } + System.Threading.CancellationTokenSource CancellationTokenSource { get; set; } + System.Collections.Generic.IDictionary ExtensibleParameters { get; } + HttpPipeline Pipeline { get; set; } + Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.DataBoundary Client { get; } + } +} diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/ConversionException.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/ConversionException.cs new file mode 100644 index 000000000000..15e049bcc8d3 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/IJsonConverter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/IJsonConverter.cs new file mode 100644 index 000000000000..dd3d2196929f --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.Runtime.Json +{ + internal interface IJsonConverter + { + JsonNode ToJson(object value); + + object FromJson(JsonNode node); + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/BinaryConverter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/BinaryConverter.cs new file mode 100644 index 000000000000..7ba117623384 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/BooleanConverter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/BooleanConverter.cs new file mode 100644 index 000000000000..e428f9ed1997 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/DateTimeConverter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/DateTimeConverter.cs new file mode 100644 index 000000000000..867923e7f55f --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs new file mode 100644 index 000000000000..9c15cdfcdd36 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/DecimalConverter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/DecimalConverter.cs new file mode 100644 index 000000000000..dc14001f21cf --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/DoubleConverter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/DoubleConverter.cs new file mode 100644 index 000000000000..5352a8f8231f --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/EnumConverter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/EnumConverter.cs new file mode 100644 index 000000000000..34bd704e0d18 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/GuidConverter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/GuidConverter.cs new file mode 100644 index 000000000000..0c303c32fe70 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/HashSet'1Converter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/HashSet'1Converter.cs new file mode 100644 index 000000000000..074a198d4f55 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/Int16Converter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/Int16Converter.cs new file mode 100644 index 000000000000..9891061e954c --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/Int32Converter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/Int32Converter.cs new file mode 100644 index 000000000000..6c8675334e5c --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/Int64Converter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/Int64Converter.cs new file mode 100644 index 000000000000..2b9e7d386ed0 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/JsonArrayConverter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/JsonArrayConverter.cs new file mode 100644 index 000000000000..4c5c00f08d38 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/JsonObjectConverter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/JsonObjectConverter.cs new file mode 100644 index 000000000000..1ac88d65be71 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/SingleConverter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/SingleConverter.cs new file mode 100644 index 000000000000..4d41f316eb2c --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/StringConverter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/StringConverter.cs new file mode 100644 index 000000000000..875c6afda0e2 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/TimeSpanConverter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/TimeSpanConverter.cs new file mode 100644 index 000000000000..c34eb884e583 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/UInt16Converter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/UInt16Converter.cs new file mode 100644 index 000000000000..ab98b136c5cb --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/UInt32Converter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/UInt32Converter.cs new file mode 100644 index 000000000000..b7f8530f1648 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/UInt64Converter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/UInt64Converter.cs new file mode 100644 index 000000000000..2ad18009a192 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/UriConverter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/Instances/UriConverter.cs new file mode 100644 index 000000000000..c9a5e458055d --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/JsonConverter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/JsonConverter.cs new file mode 100644 index 000000000000..b5d47c0d06c5 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/JsonConverterAttribute.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/JsonConverterAttribute.cs new file mode 100644 index 000000000000..e3d5bec9ac8f --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/JsonConverterFactory.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/JsonConverterFactory.cs new file mode 100644 index 000000000000..1224f3054aed --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Conversions/StringLikeConverter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Conversions/StringLikeConverter.cs new file mode 100644 index 000000000000..357261fe3197 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Customizations/IJsonSerializable.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Customizations/IJsonSerializable.cs new file mode 100644 index 000000000000..7f98899c9bd8 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/Customizations/IJsonSerializable.cs @@ -0,0 +1,263 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.Runtime.Json; +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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); + } + + // DictionaryEntity struct type + if (vValue is System.Collections.DictionaryEntry deValue) + { + return new JsonObject { { deValue.Key.ToString(), ToJsonValue(deValue.Value) } }; + } + + // 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.DataBoundary.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.DataBoundary.Runtime.JsonSerializable.ToJson(dictionary, null); + } + + // hashtables are converted to dictionaries for serialization + if (value is System.Collections.Hashtable hashtable) + { + var dict = new System.Collections.Generic.Dictionary(); + DictionaryExtensions.HashTableToDictionary(hashtable, dict); + return Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.JsonSerializable.ToJson(dict, 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/Resources/DataBoundary.Autorest/generated/runtime/Customizations/JsonArray.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Customizations/JsonArray.cs new file mode 100644 index 000000000000..7cb8905a3c61 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Customizations/JsonBoolean.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Customizations/JsonBoolean.cs new file mode 100644 index 000000000000..df862ad83825 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Customizations/JsonNode.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Customizations/JsonNode.cs new file mode 100644 index 000000000000..88fce68bb9fb --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Customizations/JsonNumber.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Customizations/JsonNumber.cs new file mode 100644 index 000000000000..883735b4f4c1 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Customizations/JsonObject.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Customizations/JsonObject.cs new file mode 100644 index 000000000000..70210b013669 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.Runtime.Json +{ + using System; + using System.Collections.Generic; + + public partial class JsonObject + { + internal override object ToValue() => Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Customizations/JsonString.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Customizations/JsonString.cs new file mode 100644 index 000000000000..236846725360 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Customizations/XNodeArray.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Customizations/XNodeArray.cs new file mode 100644 index 000000000000..f394df6dbb8e --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Debugging.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Debugging.cs new file mode 100644 index 000000000000..241a7877541e --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/DictionaryExtensions.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/DictionaryExtensions.cs new file mode 100644 index 000000000000..5ebcf217a7ee --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/DictionaryExtensions.cs @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.Runtime +{ + internal static class DictionaryExtensions + { + internal static void HashTableToDictionary(System.Collections.Hashtable hashtable, System.Collections.Generic.IDictionary dictionary) + { + if (null == hashtable) + { + return; + } + foreach (var each in hashtable.Keys) + { + var key = each.ToString(); + var value = hashtable[key]; + if (null != value) + { + 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/Resources/DataBoundary.Autorest/generated/runtime/EventData.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/EventData.cs new file mode 100644 index 000000000000..9a38f2aef7bb --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/EventDataExtensions.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/EventDataExtensions.cs new file mode 100644 index 000000000000..7d3b9304b84f --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.Runtime +{ + using System; + + /// + /// 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. + /// + [System.ComponentModel.TypeConverter(typeof(EventDataConverter))] + 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/Resources/DataBoundary.Autorest/generated/runtime/EventListener.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/EventListener.cs new file mode 100644 index 000000000000..301ffe9914a4 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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.DataBoundary.Runtime.Extensions; + + public interface IValidates + { + Task Validate(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.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.DataBoundary.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Events.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Events.cs new file mode 100644 index 000000000000..81b89d1bc5e1 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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); + public const string Progress = nameof(Progress); + } +} diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/EventsExtensions.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/EventsExtensions.cs new file mode 100644 index 000000000000..97530c5a4584 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Extensions.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Extensions.cs new file mode 100644 index 000000000000..866e2617c754 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/Extensions.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. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime +{ + using System.Linq; + using System; + + internal static partial class Extensions + { + public static T[] SubArray(this T[] array, int offset, int length) + { + return new ArraySegment(array, offset, length) + .ToArray(); + } + + 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.DataBoundary.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.DataBoundary.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 => string.Equals(headerName, each.Key, System.StringComparison.OrdinalIgnoreCase)).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/Resources/DataBoundary.Autorest/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs new file mode 100644 index 000000000000..7affbd2707ae --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Helpers/Extensions/TypeExtensions.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Helpers/Extensions/TypeExtensions.cs new file mode 100644 index 000000000000..ae28d5369623 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Helpers/Seperator.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Helpers/Seperator.cs new file mode 100644 index 000000000000..57f8043dfd53 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.Runtime.Json +{ + internal static class Seperator + { + internal static readonly char[] Dash = { '-' }; + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/Helpers/TypeDetails.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Helpers/TypeDetails.cs new file mode 100644 index 000000000000..35d1067fe823 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Helpers/XHelper.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Helpers/XHelper.cs new file mode 100644 index 000000000000..0672b271d597 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/HttpPipeline.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/HttpPipeline.cs new file mode 100644 index 000000000000..e1d656e8a4fe --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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 delegation 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; + } + } +} diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/HttpPipelineMocking.ps1 b/src/Resources/DataBoundary.Autorest/generated/runtime/HttpPipelineMocking.ps1 new file mode 100644 index 000000000000..b71d7b1d8393 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/IAssociativeArray.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/IAssociativeArray.cs new file mode 100644 index 000000000000..dbae904be7db --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/IAssociativeArray.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. + *--------------------------------------------------------------------------------------------*/ +#define DICT_PROPERTIES +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime +{ + /// A subset of IDictionary that doesn't implement IEnumerable or IDictionary to work around PowerShell's aggressive formatter + public interface IAssociativeArray + { +#if DICT_PROPERTIES + System.Collections.Generic.IEnumerable Keys { get; } + System.Collections.Generic.IEnumerable Values { get; } + int Count { get; } +#endif + System.Collections.Generic.IDictionary AdditionalProperties { get; } + T this[string index] { get; set; } + 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/Resources/DataBoundary.Autorest/generated/runtime/IHeaderSerializable.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/IHeaderSerializable.cs new file mode 100644 index 000000000000..dd7179b1daaf --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.Runtime +{ + public interface IHeaderSerializable + { + void ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers); + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/ISendAsync.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/ISendAsync.cs new file mode 100644 index 000000000000..796c3645f8cd --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/ISendAsync.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. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime +{ + using System.Net.Http; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using System.Collections; + using System.Linq; + using System; + + + /// + /// 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 const int DefaultMaxRetry = 3; + 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 }; + + private bool shouldRetry429(HttpResponseMessage response) + { + if (response.StatusCode == (System.Net.HttpStatusCode)429) + { + var retryAfter = response.Headers.RetryAfter; + if (retryAfter != null && retryAfter.Delta.HasValue) + { + return true; + } + } + return false; + } + /// + /// The step to handle 429 response with retry-after header. + /// + public async Task Retry429(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + int retryCount = int.MaxValue; + + try + { + try + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("PS_HTTP_MAX_RETRIES_FOR_429")); + } + finally + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("AZURE_PS_HTTP_MAX_RETRIES_FOR_429")); + } + } + catch (System.Exception) + { + //no action + } + var cloneRequest = await request.CloneWithContent(); + var response = await next.SendAsync(request, callback); + int count = 0; + while (shouldRetry429(response) && count++ < retryCount) + { + request = await cloneRequest.CloneWithContent(); + var retryAfter = response.Headers.RetryAfter; + await Task.Delay(retryAfter.Delta.Value, callback.Token); + await callback.Signal("Debug", $"Start to retry {count} time(s) on status code 429 after waiting {retryAfter.Delta.Value.TotalSeconds} seconds."); + response = await next.SendAsync(request, callback); + } + return response; + } + + private bool shouldRetryError(HttpResponseMessage response) + { + if (response.StatusCode >= System.Net.HttpStatusCode.InternalServerError) + { + if (response.StatusCode != System.Net.HttpStatusCode.NotImplemented && + response.StatusCode != System.Net.HttpStatusCode.HttpVersionNotSupported) + { + return true; + } + } + else if (response.StatusCode == System.Net.HttpStatusCode.RequestTimeout) + { + return true; + } + else if (response.StatusCode == (System.Net.HttpStatusCode)429 && response.Headers.RetryAfter == null) + { + return true; + } + return false; + } + + /// + /// Returns true if status code in HttpRequestExceptionWithStatus exception is greater + /// than or equal to 500 and not NotImplemented (501) or HttpVersionNotSupported (505). + /// Or it's 429 (TOO MANY REQUESTS) without Retry-After header. + /// + public async Task RetryError(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + int retryCount = DefaultMaxRetry; + + try + { + try + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("PS_HTTP_MAX_RETRIES")); + } + finally + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("AZURE_PS_HTTP_MAX_RETRIES")); + } + } + catch (System.Exception) + { + //no action + } + var cloneRequest = await request.CloneWithContent(); + var response = await next.SendAsync(request, callback); + int count = 0; + while (shouldRetryError(response) && count++ < retryCount) + { + await callback.Signal("Debug", $"Start to retry {count} time(s) on status code {response.StatusCode}"); + request = await cloneRequest.CloneWithContent(); + response = await next.SendAsync(request, callback); + } + return response; + } + + 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(); + if (Convert.ToBoolean(@"true")) + { + next = (new SendAsyncFactory(Retry429)).Create(next) ?? next; + next = (new SendAsyncFactory(RetryError)).Create(next) ?? next; + } + 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) + { + /* + **temporarily skip cloning telemetry related headers** + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); + */ + if (!"x-ms-unique-id".Equals(header.Key) && !"x-ms-client-request-id".Equals(header.Key) && !"CommandName".Equals(header.Key) && !"FullCommandName".Equals(header.Key) && !"ParameterSetName".Equals(header.Key) && !"User-Agent".Equals(header.Key)) + { + 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; + } + } +} diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/InfoAttribute.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/InfoAttribute.cs new file mode 100644 index 000000000000..7aebd1d9782c --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/InfoAttribute.cs @@ -0,0 +1,38 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.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 bool Read { get; set; } = true; + public bool Create { get; set; } = true; + public bool Update { get; set; } = true; + 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; } = ""; + public string SetCondition { get; set; } = ""; + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/InputHandler.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/InputHandler.cs new file mode 100644 index 000000000000..ee5c21c3823b --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/InputHandler.cs @@ -0,0 +1,22 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.Runtime.Cmdlets +{ + public abstract class InputHandler + { + protected InputHandler NextHandler = null; + + public void SetNextHandler(InputHandler nextHandler) + { + this.NextHandler = nextHandler; + } + + public abstract void Process(Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.IContext context); + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/Iso/IsoDate.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Iso/IsoDate.cs new file mode 100644 index 000000000000..c9018e7f7109 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/JsonType.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/JsonType.cs new file mode 100644 index 000000000000..c0ac0b1bfeee --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/MessageAttribute.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/MessageAttribute.cs new file mode 100644 index 000000000000..719883ec46ac --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/MessageAttribute.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. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.generated.runtime.Properties; + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Management.Automation; + using System.Text; + + [AttributeUsage(AttributeTargets.All)] + public class GenericBreakingChangeAttribute : Attribute + { + private string _message; + //A dexcription of what the change is about, non mandatory + public string ChangeDescription { get; set; } = null; + + //The version the change is effective from, non mandatory + public string DeprecateByVersion { get; } + public string DeprecateByAzVersion { get; } + + //The date on which the change comes in effect + public DateTime ChangeInEfectByDate { get; } + public bool ChangeInEfectByDateSet { get; } = false; + + //Old way of calling the cmdlet + public string OldWay { get; set; } + //New way fo calling the cmdlet + public string NewWay { get; set; } + + public GenericBreakingChangeAttribute(string message, string deprecateByAzVersion, string deprecateByVersion) + { + _message = message; + this.DeprecateByAzVersion = deprecateByAzVersion; + this.DeprecateByVersion = deprecateByVersion; + } + + public GenericBreakingChangeAttribute(string message, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) + { + _message = message; + this.DeprecateByVersion = deprecateByVersion; + this.DeprecateByAzVersion = deprecateByAzVersion; + + if (DateTime.TryParse(changeInEfectByDate, new CultureInfo("en-US"), DateTimeStyles.None, out DateTime result)) + { + this.ChangeInEfectByDate = result; + this.ChangeInEfectByDateSet = true; + } + } + + public DateTime getInEffectByDate() + { + return this.ChangeInEfectByDate.Date; + } + + + /** + * This function prints out the breaking change message for the attribute on the cmdline + * */ + public void PrintCustomAttributeInfo(Action writeOutput) + { + + if (!GetAttributeSpecificMessage().StartsWith(Environment.NewLine)) + { + writeOutput(Environment.NewLine); + } + writeOutput(string.Format(Resources.BreakingChangesAttributesDeclarationMessage, GetAttributeSpecificMessage())); + + + if (!string.IsNullOrWhiteSpace(ChangeDescription)) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesChangeDescriptionMessage, this.ChangeDescription)); + } + + if (ChangeInEfectByDateSet) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByDateMessage, this.ChangeInEfectByDate.ToString("d"))); + } + + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByAzVersion, this.DeprecateByAzVersion)); + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByVersion, this.DeprecateByVersion)); + + if (OldWay != null && NewWay != null) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesUsageChangeMessageConsole, OldWay, NewWay)); + } + } + + public virtual bool IsApplicableToInvocation(InvocationInfo invocation) + { + return true; + } + + protected virtual string GetAttributeSpecificMessage() + { + return _message; + } + } + + [AttributeUsage(AttributeTargets.All)] + public class CmdletBreakingChangeAttribute : GenericBreakingChangeAttribute + { + + public string ReplacementCmdletName { get; set; } + + public CmdletBreakingChangeAttribute(string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + } + + public CmdletBreakingChangeAttribute(string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + } + + protected override string GetAttributeSpecificMessage() + { + if (string.IsNullOrWhiteSpace(ReplacementCmdletName)) + { + return Resources.BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement; + } + else + { + return string.Format(Resources.BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement, ReplacementCmdletName); + } + } + } + + [AttributeUsage(AttributeTargets.All)] + public class ParameterSetBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string[] ChangedParameterSet { set; get; } + + public ParameterSetBreakingChangeAttribute(string[] changedParameterSet, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + ChangedParameterSet = changedParameterSet; + } + + public ParameterSetBreakingChangeAttribute(string[] changedParameterSet, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + ChangedParameterSet = changedParameterSet; + } + + protected override string GetAttributeSpecificMessage() + { + + return Resources.BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement; + + } + + public bool IsApplicableToInvocation(InvocationInfo invocation, string parameterSetName) + { + if (ChangedParameterSet != null) + return ChangedParameterSet.Contains(parameterSetName); + return false; + } + + } + + [AttributeUsage(AttributeTargets.All)] + public class PreviewMessageAttribute : Attribute + { + public string _message; + + public DateTime EstimatedGaDate { get; } + + public bool IsEstimatedGaDateSet { get; } = false; + + + public PreviewMessageAttribute() + { + this._message = Resources.PreviewCmdletMessage; + } + + public PreviewMessageAttribute(string message) + { + this._message = string.IsNullOrEmpty(message) ? Resources.PreviewCmdletMessage : message; + } + + public PreviewMessageAttribute(string message, string estimatedDateOfGa) : this(message) + { + if (DateTime.TryParse(estimatedDateOfGa, new CultureInfo("en-US"), DateTimeStyles.None, out DateTime result)) + { + this.EstimatedGaDate = result; + this.IsEstimatedGaDateSet = true; + } + } + + public void PrintCustomAttributeInfo(Action writeOutput) + { + writeOutput(this._message); + + if (IsEstimatedGaDateSet) + { + writeOutput(string.Format(Resources.PreviewCmdletETAMessage, this.EstimatedGaDate.ToShortDateString())); + } + } + + public virtual bool IsApplicableToInvocation(InvocationInfo invocation) + { + return true; + } + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class ParameterBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string NameOfParameterChanging { get; } + + public string ReplaceMentCmdletParameterName { get; set; } = null; + + public bool IsBecomingMandatory { get; set; } = false; + + public String OldParamaterType { get; set; } + + public String NewParameterType { get; set; } + + public ParameterBreakingChangeAttribute(string nameOfParameterChanging, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + this.NameOfParameterChanging = nameOfParameterChanging; + } + + public ParameterBreakingChangeAttribute(string nameOfParameterChanging, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + this.NameOfParameterChanging = nameOfParameterChanging; + } + + protected override string GetAttributeSpecificMessage() + { + StringBuilder message = new StringBuilder(); + if (!string.IsNullOrWhiteSpace(ReplaceMentCmdletParameterName)) + { + if (IsBecomingMandatory) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterReplacedMandatory, NameOfParameterChanging, ReplaceMentCmdletParameterName)); + } + else + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterReplaced, NameOfParameterChanging, ReplaceMentCmdletParameterName)); + } + } + else + { + if (IsBecomingMandatory) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterMandatoryNow, NameOfParameterChanging)); + } + else + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterChanging, NameOfParameterChanging)); + } + } + + //See if the type of the param is changing + if (OldParamaterType != null && !string.IsNullOrWhiteSpace(NewParameterType)) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterTypeChange, OldParamaterType, NewParameterType)); + } + return message.ToString(); + } + + /// + /// See if the bound parameters contain the current parameter, if they do + /// then the attribbute is applicable + /// If the invocationInfo is null we return true + /// + /// + /// bool + public override bool IsApplicableToInvocation(InvocationInfo invocationInfo) + { + bool? applicable = invocationInfo == null ? true : invocationInfo.BoundParameters?.Keys?.Contains(this.NameOfParameterChanging); + return applicable.HasValue ? applicable.Value : false; + } + } + + [AttributeUsage(AttributeTargets.All)] + public class OutputBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string DeprecatedCmdLetOutputType { get; } + + //This is still a String instead of a Type as this + //might be undefined at the time of adding the attribute + public string ReplacementCmdletOutputType { get; set; } + + public string[] DeprecatedOutputProperties { get; set; } + + public string[] NewOutputProperties { get; set; } + + public OutputBreakingChangeAttribute(string deprecatedCmdletOutputType, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + this.DeprecatedCmdLetOutputType = deprecatedCmdletOutputType; + } + + public OutputBreakingChangeAttribute(string deprecatedCmdletOutputType, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + this.DeprecatedCmdLetOutputType = deprecatedCmdletOutputType; + } + + protected override string GetAttributeSpecificMessage() + { + StringBuilder message = new StringBuilder(); + + //check for the deprecation scenario + if (string.IsNullOrWhiteSpace(ReplacementCmdletOutputType) && NewOutputProperties == null && DeprecatedOutputProperties == null && string.IsNullOrWhiteSpace(ChangeDescription)) + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputTypeDeprecated, DeprecatedCmdLetOutputType)); + } + else + { + if (!string.IsNullOrWhiteSpace(ReplacementCmdletOutputType)) + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputChange1, DeprecatedCmdLetOutputType, ReplacementCmdletOutputType)); + } + else + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputChange2, DeprecatedCmdLetOutputType)); + } + + if (DeprecatedOutputProperties != null && DeprecatedOutputProperties.Length > 0) + { + message.Append(Resources.BreakingChangesAttributesCmdLetOutputPropertiesRemoved); + foreach (string property in DeprecatedOutputProperties) + { + message.Append(" '" + property + "'"); + } + } + + if (NewOutputProperties != null && NewOutputProperties.Length > 0) + { + message.Append(Resources.BreakingChangesAttributesCmdLetOutputPropertiesAdded); + foreach (string property in NewOutputProperties) + { + message.Append(" '" + property + "'"); + } + } + } + return message.ToString(); + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/MessageAttributeHelper.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/MessageAttributeHelper.cs new file mode 100644 index 000000000000..106a680780f3 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/MessageAttributeHelper.cs @@ -0,0 +1,184 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.generated.runtime.Properties; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Management.Automation; + using System.Reflection; + using System.Text; + using System.Threading.Tasks; + public class MessageAttributeHelper + { + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + public const string BREAKING_CHANGE_ATTRIBUTE_INFORMATION_LINK = "https://aka.ms/azps-changewarnings"; + public const string SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME = "SuppressAzurePowerShellBreakingChangeWarnings"; + + /** + * This function takes in a CommandInfo (CmdletInfo or FunctionInfo) + * And reads all the deprecation attributes attached to it + * Prints a message on the cmdline For each of the attribute found + * + * the boundParameterNames is a list of parameters bound to the cmdlet at runtime, + * We only process the Parameter beaking change attributes attached only params listed in this list (if present) + * */ + public static void ProcessCustomAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet, bool showPreviewMessage = true) + { + bool supressWarningOrError = false; + + try + { + supressWarningOrError = bool.Parse(System.Environment.GetEnvironmentVariable(SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME)); + } + catch (Exception) + { + //no action + } + + if (supressWarningOrError) + { + //Do not process the attributes at runtime... The env variable to override the warning messages is set + return; + } + if (IsAzure && invocationInfo.BoundParameters.ContainsKey("DefaultProfile")) + { + psCmdlet.WriteWarning("The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription."); + } + + ProcessBreakingChangeAttributesAtRuntime(commandInfo, invocationInfo, parameterSet, psCmdlet); + + } + + private static void ProcessBreakingChangeAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet) + { + List attributes = new List(GetAllBreakingChangeAttributesInType(commandInfo, invocationInfo, parameterSet)); + StringBuilder sb = new StringBuilder(); + Action appendAttributeMessage = (string s) => sb.Append(s); + + if (attributes != null && attributes.Count > 0) + { + appendAttributeMessage(string.Format(Resources.BreakingChangesAttributesHeaderMessage, commandInfo.Name.Split('_')[0])); + + foreach (GenericBreakingChangeAttribute attribute in attributes) + { + attribute.PrintCustomAttributeInfo(appendAttributeMessage); + } + + appendAttributeMessage(string.Format(Resources.BreakingChangesAttributesFooterMessage, BREAKING_CHANGE_ATTRIBUTE_INFORMATION_LINK)); + + psCmdlet.WriteWarning(sb.ToString()); + } + } + + + public static void ProcessPreviewMessageAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet) + { + List previewAttributes = new List(GetAllPreviewAttributesInType(commandInfo, invocationInfo)); + StringBuilder sb = new StringBuilder(); + Action appendAttributeMessage = (string s) => sb.Append(s); + + if (previewAttributes != null && previewAttributes.Count > 0) + { + foreach (PreviewMessageAttribute attribute in previewAttributes) + { + attribute.PrintCustomAttributeInfo(appendAttributeMessage); + } + psCmdlet.WriteWarning(sb.ToString()); + } + } + + /** + * This function takes in a CommandInfo (CmdletInfo or FunctionInfo) + * And returns all the deprecation attributes attached to it + * + * the boundParameterNames is a list of parameters bound to the cmdlet at runtime, + * We only process the Parameter beaking change attributes attached only params listed in this list (if present) + **/ + private static IEnumerable GetAllBreakingChangeAttributesInType(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet) + { + List attributeList = new List(); + + if (commandInfo.GetType() == typeof(CmdletInfo)) + { + var type = ((CmdletInfo)commandInfo).ImplementingType; + attributeList.AddRange(type.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + + foreach (MethodInfo m in type.GetRuntimeMethods()) + { + attributeList.AddRange((m.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast())); + } + + foreach (FieldInfo f in type.GetRuntimeFields()) + { + attributeList.AddRange(f.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + } + + foreach (PropertyInfo p in type.GetRuntimeProperties()) + { + attributeList.AddRange(p.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + } + } + else if (commandInfo.GetType() == typeof(FunctionInfo)) + { + attributeList.AddRange(((FunctionInfo)commandInfo).ScriptBlock.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast()); + foreach (var parameter in ((FunctionInfo)commandInfo).Parameters) + { + attributeList.AddRange(parameter.Value.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast()); + } + } + return invocationInfo == null ? attributeList : attributeList.Where(e => e.GetType() == typeof(ParameterSetBreakingChangeAttribute) ? ((ParameterSetBreakingChangeAttribute)e).IsApplicableToInvocation(invocationInfo, parameterSet) : e.IsApplicableToInvocation(invocationInfo)); + } + + public static bool ContainsPreviewAttribute(CommandInfo commandInfo, InvocationInfo invocationInfo) + { + return GetAllPreviewAttributesInType(commandInfo, invocationInfo)?.Count() > 0; + } + + private static IEnumerable GetAllPreviewAttributesInType(CommandInfo commandInfo, InvocationInfo invocationInfo) + { + List attributeList = new List(); + if (commandInfo.GetType() == typeof(CmdletInfo)) + { + var type = ((CmdletInfo)commandInfo).ImplementingType; + attributeList.AddRange(type.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + + foreach (MethodInfo m in type.GetRuntimeMethods()) + { + attributeList.AddRange((m.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast())); + } + + foreach (FieldInfo f in type.GetRuntimeFields()) + { + attributeList.AddRange(f.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + } + + foreach (PropertyInfo p in type.GetRuntimeProperties()) + { + attributeList.AddRange(p.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + } + } + else if (commandInfo.GetType() == typeof(FunctionInfo)) + { + attributeList.AddRange(((FunctionInfo)commandInfo).ScriptBlock.Attributes.Where(e => typeof(PreviewMessageAttribute).IsAssignableFrom(e.GetType())).Cast()); + foreach (var parameter in ((FunctionInfo)commandInfo).Parameters) + { + attributeList.AddRange(parameter.Value.Attributes.Where(e => typeof(PreviewMessageAttribute).IsAssignableFrom(e.GetType())).Cast()); + } + } + return invocationInfo == null ? attributeList : attributeList.Where(e => e.IsApplicableToInvocation(invocationInfo)); + } + } +} diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/Method.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Method.cs new file mode 100644 index 000000000000..419dbfed91be --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Models/JsonMember.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Models/JsonMember.cs new file mode 100644 index 000000000000..d0f645d0b955 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Models/JsonModel.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Models/JsonModel.cs new file mode 100644 index 000000000000..013f4d7048aa --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Models/JsonModelCache.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Models/JsonModelCache.cs new file mode 100644 index 000000000000..ea66c90f1880 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Nodes/Collections/JsonArray.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Nodes/Collections/JsonArray.cs new file mode 100644 index 000000000000..40723ef7316a --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Nodes/Collections/XImmutableArray.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Nodes/Collections/XImmutableArray.cs new file mode 100644 index 000000000000..8085e028d8be --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Nodes/Collections/XList.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Nodes/Collections/XList.cs new file mode 100644 index 000000000000..483937770efd --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Nodes/Collections/XNodeArray.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Nodes/Collections/XNodeArray.cs new file mode 100644 index 000000000000..662c945b555c --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/Nodes/Collections/XNodeArray.cs @@ -0,0 +1,73 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.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); + } + + internal XNodeArray(System.Collections.Generic.List 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/Resources/DataBoundary.Autorest/generated/runtime/Nodes/Collections/XSet.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Nodes/Collections/XSet.cs new file mode 100644 index 000000000000..0bd7b4bf5a50 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Nodes/JsonBoolean.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Nodes/JsonBoolean.cs new file mode 100644 index 000000000000..b52ec7943226 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Nodes/JsonDate.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Nodes/JsonDate.cs new file mode 100644 index 000000000000..ee6ed62709f8 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Nodes/JsonNode.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Nodes/JsonNode.cs new file mode 100644 index 000000000000..a1ce47a6086e --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Nodes/JsonNumber.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Nodes/JsonNumber.cs new file mode 100644 index 000000000000..50244a1a7910 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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(System.Globalization.CultureInfo.InvariantCulture); + } + + internal JsonNumber(double value) + { + this.value = value.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + 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, System.Globalization.CultureInfo.InvariantCulture); + + public static implicit operator Double(JsonNumber number) + => double.Parse(number.value, System.Globalization.CultureInfo.InvariantCulture); + + public static implicit operator float(JsonNumber number) + => float.Parse(number.value, System.Globalization.CultureInfo.InvariantCulture); + + 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/Resources/DataBoundary.Autorest/generated/runtime/Nodes/JsonObject.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Nodes/JsonObject.cs new file mode 100644 index 000000000000..98228cbb266d --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Nodes/JsonString.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Nodes/JsonString.cs new file mode 100644 index 000000000000..98036461b221 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Nodes/XBinary.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Nodes/XBinary.cs new file mode 100644 index 000000000000..c8e0f3cbf0dd --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Nodes/XNull.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Nodes/XNull.cs new file mode 100644 index 000000000000..46e82decd483 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Parser/Exceptions/ParseException.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Parser/Exceptions/ParseException.cs new file mode 100644 index 000000000000..443448b282bb --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Parser/JsonParser.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Parser/JsonParser.cs new file mode 100644 index 000000000000..bf6b1cb01890 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Parser/JsonToken.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Parser/JsonToken.cs new file mode 100644 index 000000000000..c909d1f7159a --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Parser/JsonTokenizer.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Parser/JsonTokenizer.cs new file mode 100644 index 000000000000..57ef7cec9ac4 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Parser/Location.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Parser/Location.cs new file mode 100644 index 000000000000..b9f4b5e29e68 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Parser/Readers/SourceReader.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Parser/Readers/SourceReader.cs new file mode 100644 index 000000000000..422543769a95 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Parser/TokenReader.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Parser/TokenReader.cs new file mode 100644 index 000000000000..edbdc441005b --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/PipelineMocking.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/PipelineMocking.cs new file mode 100644 index 000000000000..5153c58ed0d0 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/PipelineMocking.cs @@ -0,0 +1,262 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.Runtime +{ + using System.Threading.Tasks; + using System.Collections.Generic; + using System.Net.Http; + using System.Linq; + using System.Net; + using Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.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, ref bool isBase64) => content == null ? XNull.Instance : SerializeContent(content.ReadAsByteArrayAsync().Result, ref isBase64); + + internal static JsonNode SerializeContent(byte[] content, ref bool isBase64) + { + 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, bool isBase64) + { + if (string.IsNullOrWhiteSpace(content)) + { + return new byte[0]; + } + + if (isBase64) + { + 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(); + bool isBase64Request = false; + bool isBase64Response = false; + messages[rqKey] = new JsonObject { + { "Request",new JsonObject { + { "Method", request.Method.Method }, + { "RequestUri", request.RequestUri }, + { "Content", SerializeContent( request.Content, ref isBase64Request) }, + { "isContentBase64", isBase64Request }, + { "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, ref isBase64Response) }, + { "isContentBase64", isBase64Response }, + }} + }; + 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 ---------------------------------------------------------------- + bool isBase64Response = false; + respMessage.BooleanProperty("isContentBase64", ref isBase64Response); + var response = new HttpResponseMessage + { + StatusCode = (HttpStatusCode)respMessage.NumberProperty("StatusCode", ref sc), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(respMessage.StringProperty("Content"), isBase64Response)) + }; + + 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 ---------------------------------------------------------------- + bool isBase64Request = false; + reqMessage.BooleanProperty("isContentBase64", ref isBase64Request); + 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"), isBase64Request)) + }; + + 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); + } + } + } +} diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/Properties/Resources.Designer.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Properties/Resources.Designer.cs new file mode 100644 index 000000000000..bebaf5f7ca24 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/Properties/Resources.Designer.cs @@ -0,0 +1,5655 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.generated.runtime.Properties +{ + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + public class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Resources.ResourceManager ResourceManager + { + get + { + if (object.ReferenceEquals(resourceMan, null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.generated.runtime.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to The remote server returned an error: (401) Unauthorized.. + /// + public static string AccessDeniedExceptionMessage + { + get + { + return ResourceManager.GetString("AccessDeniedExceptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account id doesn't match one in subscription.. + /// + public static string AccountIdDoesntMatchSubscription + { + get + { + return ResourceManager.GetString("AccountIdDoesntMatchSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account needs to be specified. + /// + public static string AccountNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("AccountNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account "{0}" has been added.. + /// + public static string AddAccountAdded + { + get + { + return ResourceManager.GetString("AddAccountAdded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To switch to a different subscription, please use Select-AzureSubscription.. + /// + public static string AddAccountChangeSubscription + { + get + { + return ResourceManager.GetString("AddAccountChangeSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Skipping external tenant {0}, because you are using a guest or a foreign principal object identity. In order to access this tenant, please run Add-AzureAccount without "-Credential".. + /// + public static string AddAccountNonInteractiveGuestOrFpo + { + get + { + return ResourceManager.GetString("AddAccountNonInteractiveGuestOrFpo", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription "{0}" is selected as the default subscription.. + /// + public static string AddAccountShowDefaultSubscription + { + get + { + return ResourceManager.GetString("AddAccountShowDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To view all the subscriptions, please use Get-AzureSubscription.. + /// + public static string AddAccountViewSubscriptions + { + get + { + return ResourceManager.GetString("AddAccountViewSubscriptions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} is created successfully.. + /// + public static string AddOnCreatedMessage + { + get + { + return ResourceManager.GetString("AddOnCreatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-on name {0} is already used.. + /// + public static string AddOnNameAlreadyUsed + { + get + { + return ResourceManager.GetString("AddOnNameAlreadyUsed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} not found.. + /// + public static string AddOnNotFound + { + get + { + return ResourceManager.GetString("AddOnNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-on {0} is removed successfully.. + /// + public static string AddOnRemovedMessage + { + get + { + return ResourceManager.GetString("AddOnRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} is updated successfully.. + /// + public static string AddOnUpdatedMessage + { + get + { + return ResourceManager.GetString("AddOnUpdatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}.. + /// + public static string AddRoleMessageCreate + { + get + { + return ResourceManager.GetString("AddRoleMessageCreate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for Node.js by running ‘npm install azure’.. + /// + public static string AddRoleMessageCreateNode + { + get + { + return ResourceManager.GetString("AddRoleMessageCreateNode", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for PHP by running "pear WindowsAzure/WindowsAzure".. + /// + public static string AddRoleMessageCreatePHP + { + get + { + return ResourceManager.GetString("AddRoleMessageCreatePHP", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to set role permissions. Please give the 'Network Service' user 'Read & execute' and 'Modify' permissions to the role folder, or run PowerShell as an Administrator. + /// + public static string AddRoleMessageInsufficientPermissions + { + get + { + return ResourceManager.GetString("AddRoleMessageInsufficientPermissions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A role name '{0}' already exists. + /// + public static string AddRoleMessageRoleExists + { + get + { + return ResourceManager.GetString("AddRoleMessageRoleExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Profile {0} already has an endpoint with name {1}. + /// + public static string AddTrafficManagerEndpointFailed + { + get + { + return ResourceManager.GetString("AddTrafficManagerEndpointFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure PowerShell collects usage data in order to improve your experience. + ///The data is anonymous and does not include commandline argument values. + ///The data is collected by Microsoft. + /// + ///Use the Disable-AzDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Az.Accounts module. To disable data collection: PS > Disable-AzDataCollection. + ///Use the Enable-AzDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Az.Accounts module. To enable [rest of string was truncated]";. + /// + public static string ARMDataCollectionMessage + { + get + { + return ResourceManager.GetString("ARMDataCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [Common.Authentication]: Authenticating for account {0} with single tenant {1}.. + /// + public static string AuthenticatingForSingleTenant + { + get + { + return ResourceManager.GetString("AuthenticatingForSingleTenant", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Windows Azure Powershell\. + /// + public static string AzureDirectory + { + get + { + return ResourceManager.GetString("AzureDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://manage.windowsazure.com. + /// + public static string AzurePortalUrl + { + get + { + return ResourceManager.GetString("AzurePortalUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_PORTAL_URL. + /// + public static string AzurePortalUrlEnv + { + get + { + return ResourceManager.GetString("AzurePortalUrlEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Selected profile must not be null.. + /// + public static string AzureProfileMustNotBeNull + { + get + { + return ResourceManager.GetString("AzureProfileMustNotBeNull", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure SDK\{0}\. + /// + public static string AzureSdkDirectory + { + get + { + return ResourceManager.GetString("AzureSdkDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File '{0}' already exists. Use the -Force parameter to overwrite it.. + /// + public static string AzureVMDscArchiveAlreadyExists + { + get + { + return ResourceManager.GetString("AzureVMDscArchiveAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find configuration data file: {0}. + /// + public static string AzureVMDscCannotFindConfigurationDataFile + { + get + { + return ResourceManager.GetString("AzureVMDscCannotFindConfigurationDataFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Create Archive. + /// + public static string AzureVMDscCreateArchiveAction + { + get + { + return ResourceManager.GetString("AzureVMDscCreateArchiveAction", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The configuration data must be a .psd1 file. + /// + public static string AzureVMDscInvalidConfigurationDataFile + { + get + { + return ResourceManager.GetString("AzureVMDscInvalidConfigurationDataFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Parsing configuration script: {0}. + /// + public static string AzureVMDscParsingConfiguration + { + get + { + return ResourceManager.GetString("AzureVMDscParsingConfiguration", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Storage Blob '{0}' already exists. Use the -Force parameter to overwrite it.. + /// + public static string AzureVMDscStorageBlobAlreadyExists + { + get + { + return ResourceManager.GetString("AzureVMDscStorageBlobAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Upload '{0}'. + /// + public static string AzureVMDscUploadToBlobStorageAction + { + get + { + return ResourceManager.GetString("AzureVMDscUploadToBlobStorageAction", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Execution failed because a background thread could not prompt the user.. + /// + public static string BaseShouldMethodFailureReason + { + get + { + return ResourceManager.GetString("BaseShouldMethodFailureReason", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Base Uri was empty.. + /// + public static string BaseUriEmpty + { + get + { + return ResourceManager.GetString("BaseUriEmpty", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} begin processing without ParameterSet.. + /// + public static string BeginProcessingWithoutParameterSetLog + { + get + { + return ResourceManager.GetString("BeginProcessingWithoutParameterSetLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} begin processing with ParameterSet '{1}'.. + /// + public static string BeginProcessingWithParameterSetLog + { + get + { + return ResourceManager.GetString("BeginProcessingWithParameterSetLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Blob with the name {0} already exists in the account.. + /// + public static string BlobAlreadyExistsInTheAccount + { + get + { + return ResourceManager.GetString("BlobAlreadyExistsInTheAccount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://{0}.blob.core.windows.net/. + /// + public static string BlobEndpointUri + { + get + { + return ResourceManager.GetString("BlobEndpointUri", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_BLOBSTORAGE_TEMPLATE. + /// + public static string BlobEndpointUriEnv + { + get + { + return ResourceManager.GetString("BlobEndpointUriEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is changing.. + /// + public static string BreakingChangeAttributeParameterChanging + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterChanging", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is becoming mandatory.. + /// + public static string BreakingChangeAttributeParameterMandatoryNow + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterMandatoryNow", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is being replaced by parameter : '{1}'.. + /// + public static string BreakingChangeAttributeParameterReplaced + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterReplaced", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is being replaced by mandatory parameter : '{1}'.. + /// + public static string BreakingChangeAttributeParameterReplacedMandatory + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterReplacedMandatory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The type of the parameter is changing from '{0}' to '{1}'.. + /// + public static string BreakingChangeAttributeParameterTypeChange + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterTypeChange", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Change description : {0} + ///. + /// + public static string BreakingChangesAttributesChangeDescriptionMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesChangeDescriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet is being deprecated. There will be no replacement for it.. + /// + public static string BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet is being deprecated. There will be no replacement for it.. + /// + public static string BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet '{0}' is replacing this cmdlet.. + /// + public static string BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The output type is changing from the existing type :'{0}' to the new type :'{1}'. + /// + public static string BreakingChangesAttributesCmdLetOutputChange1 + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputChange1", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "The output type '{0}' is changing". + /// + public static string BreakingChangesAttributesCmdLetOutputChange2 + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputChange2", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to + ///- The following properties are being added to the output type : + ///. + /// + public static string BreakingChangesAttributesCmdLetOutputPropertiesAdded + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputPropertiesAdded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to + /// - The following properties in the output type are being deprecated : + ///. + /// + public static string BreakingChangesAttributesCmdLetOutputPropertiesRemoved + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputPropertiesRemoved", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The output type '{0}' is being deprecated without a replacement.. + /// + public static string BreakingChangesAttributesCmdLetOutputTypeDeprecated + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputTypeDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to - {0} + /// + ///. + /// + public static string BreakingChangesAttributesDeclarationMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesDeclarationMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to - Cmdlet : '{0}' + /// - {1} + ///. + /// + public static string BreakingChangesAttributesDeclarationMessageWithCmdletName + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesDeclarationMessageWithCmdletName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to NOTE : Go to {0} for steps to suppress (and other related information on) the breaking change messages.. + /// + public static string BreakingChangesAttributesFooterMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesFooterMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Breaking changes in the cmdlet '{0}' :. + /// + public static string BreakingChangesAttributesHeaderMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesHeaderMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note : This change will take effect on '{0}' + ///. + /// + public static string BreakingChangesAttributesInEffectByDateMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByDateMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note :The change is expected to take effect from version : '{0}' + /// + ///. + /// + public static string BreakingChangesAttributesInEffectByVersion + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note :The change is expected to take effect from az version : '{0}' + /// + ///. + /// + public static string BreakingChangesAttributesInEffectByAzVersion + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByAzVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ```powershell + ///# Old + ///{0} + /// + ///# New + ///{1} + ///``` + /// + ///. + /// + public static string BreakingChangesAttributesUsageChangeMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesUsageChangeMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cmdlet invocation changes : + /// Old Way : {0} + /// New Way : {1}. + /// + public static string BreakingChangesAttributesUsageChangeMessageConsole + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesUsageChangeMessageConsole", resourceCulture); + } + } + + /// + /// The cmdlet is in experimental stage. The function may not be enabled in current subscription. + /// + public static string ExperimentalCmdletMessage + { + get + { + return ResourceManager.GetString("ExperimentalCmdletMessage", resourceCulture); + } + } + + + + /// + /// Looks up a localized string similar to CACHERUNTIMEURL. + /// + public static string CacheRuntimeUrl + { + get + { + return ResourceManager.GetString("CacheRuntimeUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to cache. + /// + public static string CacheRuntimeValue + { + get + { + return ResourceManager.GetString("CacheRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to CacheRuntimeVersion. + /// + public static string CacheRuntimeVersionKey + { + get + { + return ResourceManager.GetString("CacheRuntimeVersionKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing caching version {0} for Role '{1}' (the caching version locally installed is: {2}). + /// + public static string CacheVersionWarningText + { + get + { + return ResourceManager.GetString("CacheVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot change built-in environment {0}.. + /// + public static string CannotChangeBuiltinEnvironment + { + get + { + return ResourceManager.GetString("CannotChangeBuiltinEnvironment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find {0} with name {1}.. + /// + public static string CannotFind + { + get + { + return ResourceManager.GetString("CannotFind", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deployment for service {0} with {1} slot doesn't exist. + /// + public static string CannotFindDeployment + { + get + { + return ResourceManager.GetString("CannotFindDeployment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Can't find valid Microsoft Azure role in current directory {0}. + /// + public static string CannotFindRole + { + get + { + return ResourceManager.GetString("CannotFindRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service {0} configuration file (ServiceConfiguration.Cloud.cscfg) is either null or doesn't exist. + /// + public static string CannotFindServiceConfigurationFile + { + get + { + return ResourceManager.GetString("CannotFindServiceConfigurationFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid service path! Cannot locate ServiceDefinition.csdef in current folder or parent folders.. + /// + public static string CannotFindServiceRoot + { + get + { + return ResourceManager.GetString("CannotFindServiceRoot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named {0} with id {1} is not currently imported. You must import this subscription before it can be updated.. + /// + public static string CannotUpdateUnknownSubscription + { + get + { + return ResourceManager.GetString("CannotUpdateUnknownSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ManagementCertificate. + /// + public static string CertificateElementName + { + get + { + return ResourceManager.GetString("CertificateElementName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to certificate.pfx. + /// + public static string CertificateFileName + { + get + { + return ResourceManager.GetString("CertificateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Certificate imported into CurrentUser\My\{0}. + /// + public static string CertificateImportedMessage + { + get + { + return ResourceManager.GetString("CertificateImportedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No certificate was found in the certificate store with thumbprint {0}. + /// + public static string CertificateNotFoundInStore + { + get + { + return ResourceManager.GetString("CertificateNotFoundInStore", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Your account does not have access to the private key for certificate {0}. + /// + public static string CertificatePrivateKeyAccessError + { + get + { + return ResourceManager.GetString("CertificatePrivateKeyAccessError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} {1} deployment for {2} service. + /// + public static string ChangeDeploymentStateWaitMessage + { + get + { + return ResourceManager.GetString("ChangeDeploymentStateWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cloud service {0} is in {1} state.. + /// + public static string ChangeDeploymentStatusCompleteMessage + { + get + { + return ResourceManager.GetString("ChangeDeploymentStatusCompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Changing/Removing public environment '{0}' is not allowed.. + /// + public static string ChangePublicEnvironmentMessage + { + get + { + return ResourceManager.GetString("ChangePublicEnvironmentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} is set to value {1}. + /// + public static string ChangeSettingsElementMessage + { + get + { + return ResourceManager.GetString("ChangeSettingsElementMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Changing public environment is not supported.. + /// + public static string ChangingDefaultEnvironmentNotSupported + { + get + { + return ResourceManager.GetString("ChangingDefaultEnvironmentNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Choose which publish settings file to use:. + /// + public static string ChoosePublishSettingsFile + { + get + { + return ResourceManager.GetString("ChoosePublishSettingsFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel. + /// + public static string ClientDiagnosticLevelName + { + get + { + return ResourceManager.GetString("ClientDiagnosticLevelName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1. + /// + public static string ClientDiagnosticLevelValue + { + get + { + return ResourceManager.GetString("ClientDiagnosticLevelValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to cloud_package.cspkg. + /// + public static string CloudPackageFileName + { + get + { + return ResourceManager.GetString("CloudPackageFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceConfiguration.Cloud.cscfg. + /// + public static string CloudServiceConfigurationFileName + { + get + { + return ResourceManager.GetString("CloudServiceConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-ons for {0}. + /// + public static string CloudServiceDescription + { + get + { + return ResourceManager.GetString("CloudServiceDescription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Communication could not be established. This could be due to an invalid subscription ID. Note that subscription IDs are case sensitive.. + /// + public static string CommunicationCouldNotBeEstablished + { + get + { + return ResourceManager.GetString("CommunicationCouldNotBeEstablished", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Complete. + /// + public static string CompleteMessage + { + get + { + return ResourceManager.GetString("CompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to OperationID : '{0}'. + /// + public static string ComputeCloudExceptionOperationIdMessage + { + get + { + return ResourceManager.GetString("ComputeCloudExceptionOperationIdMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to config.json. + /// + public static string ConfigurationFileName + { + get + { + return ResourceManager.GetString("ConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to VirtualMachine creation failed.. + /// + public static string CreateFailedErrorMessage + { + get + { + return ResourceManager.GetString("CreateFailedErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Creating the website failed. If this is the first website for this subscription, please create it using the management portal instead.. + /// + public static string CreateWebsiteFailed + { + get + { + return ResourceManager.GetString("CreateWebsiteFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core. + /// + public static string DataCacheClientsType + { + get + { + return ResourceManager.GetString("DataCacheClientsType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to //blobcontainer[@datacenter='{0}']. + /// + public static string DatacenterBlobQuery + { + get + { + return ResourceManager.GetString("DatacenterBlobQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft Azure PowerShell Data Collection Confirmation. + /// + public static string DataCollectionActivity + { + get + { + return ResourceManager.GetString("DataCollectionActivity", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You choose not to participate in Microsoft Azure PowerShell data collection.. + /// + public static string DataCollectionConfirmNo + { + get + { + return ResourceManager.GetString("DataCollectionConfirmNo", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This confirmation message will be dismissed in '{0}' second(s).... + /// + public static string DataCollectionConfirmTime + { + get + { + return ResourceManager.GetString("DataCollectionConfirmTime", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You choose to participate in Microsoft Azure PowerShell data collection.. + /// + public static string DataCollectionConfirmYes + { + get + { + return ResourceManager.GetString("DataCollectionConfirmYes", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The setting profile has been saved to the following path '{0}'.. + /// + public static string DataCollectionSaveFileInformation + { + get + { + return ResourceManager.GetString("DataCollectionSaveFileInformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Setting: {0} as the default and current subscription. To view other subscriptions use Get-AzureSubscription. + /// + public static string DefaultAndCurrentSubscription + { + get + { + return ResourceManager.GetString("DefaultAndCurrentSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to none. + /// + public static string DefaultFileVersion + { + get + { + return ResourceManager.GetString("DefaultFileVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There are no hostnames which could be used for validation.. + /// + public static string DefaultHostnamesValidation + { + get + { + return ResourceManager.GetString("DefaultHostnamesValidation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 8080. + /// + public static string DefaultPort + { + get + { + return ResourceManager.GetString("DefaultPort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1000. + /// + public static string DefaultRoleCachingInMB + { + get + { + return ResourceManager.GetString("DefaultRoleCachingInMB", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Auto. + /// + public static string DefaultUpgradeMode + { + get + { + return ResourceManager.GetString("DefaultUpgradeMode", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 80. + /// + public static string DefaultWebPort + { + get + { + return ResourceManager.GetString("DefaultWebPort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Delete. + /// + public static string Delete + { + get + { + return ResourceManager.GetString("Delete", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The {0} slot for service {1} is already in {2} state. + /// + public static string DeploymentAlreadyInState + { + get + { + return ResourceManager.GetString("DeploymentAlreadyInState", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The deployment in {0} slot for service {1} is removed. + /// + public static string DeploymentRemovedMessage + { + get + { + return ResourceManager.GetString("DeploymentRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.DiagnosticLevel. + /// + public static string DiagnosticLevelName + { + get + { + return ResourceManager.GetString("DiagnosticLevelName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1. + /// + public static string DiagnosticLevelValue + { + get + { + return ResourceManager.GetString("DiagnosticLevelValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The key to add already exists in the dictionary.. + /// + public static string DictionaryAddAlreadyContainsKey + { + get + { + return ResourceManager.GetString("DictionaryAddAlreadyContainsKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The array index cannot be less than zero.. + /// + public static string DictionaryCopyToArrayIndexLessThanZero + { + get + { + return ResourceManager.GetString("DictionaryCopyToArrayIndexLessThanZero", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The supplied array does not have enough room to contain the copied elements.. + /// + public static string DictionaryCopyToArrayTooShort + { + get + { + return ResourceManager.GetString("DictionaryCopyToArrayTooShort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided dns {0} doesn't exist. + /// + public static string DnsDoesNotExist + { + get + { + return ResourceManager.GetString("DnsDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft Azure Certificate. + /// + public static string EnableRemoteDesktop_FriendlyCertificateName + { + get + { + return ResourceManager.GetString("EnableRemoteDesktop_FriendlyCertificateName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Endpoint can't be retrieved for storage account. + /// + public static string EndPointNotFoundForBlobStorage + { + get + { + return ResourceManager.GetString("EndPointNotFoundForBlobStorage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} end processing.. + /// + public static string EndProcessingLog + { + get + { + return ResourceManager.GetString("EndProcessingLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To use Active Directory authentication, you must configure the ActiveDirectoryEndpoint, ActiveDirectoryTenantId, and ActiveDirectorServiceEndpointResourceId for environment of '{0}'. You can configure these properties for this environment using the Set-AzureEnvironment cmdlet.. + /// + public static string EnvironmentDoesNotSupportActiveDirectory + { + get + { + return ResourceManager.GetString("EnvironmentDoesNotSupportActiveDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The environment '{0}' already exists.. + /// + public static string EnvironmentExists + { + get + { + return ResourceManager.GetString("EnvironmentExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment name doesn't match one in subscription.. + /// + public static string EnvironmentNameDoesntMatchSubscription + { + get + { + return ResourceManager.GetString("EnvironmentNameDoesntMatchSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment name needs to be specified.. + /// + public static string EnvironmentNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("EnvironmentNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment needs to be specified.. + /// + public static string EnvironmentNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("EnvironmentNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The environment name '{0}' is not found.. + /// + public static string EnvironmentNotFound + { + get + { + return ResourceManager.GetString("EnvironmentNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to environments.xml. + /// + public static string EnvironmentsFileName + { + get + { + return ResourceManager.GetString("EnvironmentsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Error creating VirtualMachine. + /// + public static string ErrorCreatingVirtualMachine + { + get + { + return ResourceManager.GetString("ErrorCreatingVirtualMachine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to download available runtimes for location '{0}'. + /// + public static string ErrorRetrievingRuntimesForLocation + { + get + { + return ResourceManager.GetString("ErrorRetrievingRuntimesForLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Error updating VirtualMachine. + /// + public static string ErrorUpdatingVirtualMachine + { + get + { + return ResourceManager.GetString("ErrorUpdatingVirtualMachine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Job Id {0} failed. Error: {1}, ExceptionDetails: {2}. + /// + public static string FailedJobErrorMessage + { + get + { + return ResourceManager.GetString("FailedJobErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File path is not valid.. + /// + public static string FilePathIsNotValid + { + get + { + return ResourceManager.GetString("FilePathIsNotValid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The HTTP request was forbidden with client authentication scheme 'Anonymous'.. + /// + public static string FirstPurchaseErrorMessage + { + get + { + return ResourceManager.GetString("FirstPurchaseErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This add-on requires you to purchase the first instance through the Microsoft Azure Portal. Subsequent purchases can be performed through PowerShell.. + /// + public static string FirstPurchaseMessage + { + get + { + return ResourceManager.GetString("FirstPurchaseMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Operation Status:. + /// + public static string GatewayOperationStatus + { + get + { + return ResourceManager.GetString("GatewayOperationStatus", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\General. + /// + public static string GeneralScaffolding + { + get + { + return ResourceManager.GetString("GeneralScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Getting all available Microsoft Azure Add-Ons, this may take few minutes.... + /// + public static string GetAllAddOnsWaitMessage + { + get + { + return ResourceManager.GetString("GetAllAddOnsWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Name{0}Primary Key{0}Seconday Key. + /// + public static string GetStorageKeysHeader + { + get + { + return ResourceManager.GetString("GetStorageKeysHeader", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Git not found. Please install git and place it in your command line path.. + /// + public static string GitNotFound + { + get + { + return ResourceManager.GetString("GitNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Could not find publish settings. Please run Import-AzurePublishSettingsFile.. + /// + public static string GlobalSettingsManager_Load_PublishSettingsNotFound + { + get + { + return ResourceManager.GetString("GlobalSettingsManager_Load_PublishSettingsNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find the WadCfg end element in the config.. + /// + public static string IaasDiagnosticsBadConfigNoEndWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoEndWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WadCfg start element in the config is not matching the end element.. + /// + public static string IaasDiagnosticsBadConfigNoMatchingWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoMatchingWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find the WadCfg element in the config.. + /// + public static string IaasDiagnosticsBadConfigNoWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode.dll. + /// + public static string IISNodeDll + { + get + { + return ResourceManager.GetString("IISNodeDll", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode. + /// + public static string IISNodeEngineKey + { + get + { + return ResourceManager.GetString("IISNodeEngineKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode-dev\\release\\x64. + /// + public static string IISNodePath + { + get + { + return ResourceManager.GetString("IISNodePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode. + /// + public static string IISNodeRuntimeValue + { + get + { + return ResourceManager.GetString("IISNodeRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing IISNode version {0} in Azure for WebRole '{1}' (the version locally installed is: {2}). + /// + public static string IISNodeVersionWarningText + { + get + { + return ResourceManager.GetString("IISNodeVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Illegal characters in path.. + /// + public static string IllegalPath + { + get + { + return ResourceManager.GetString("IllegalPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. + /// + public static string InternalServerErrorMessage + { + get + { + return ResourceManager.GetString("InternalServerErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot enable memcach protocol on a cache worker role {0}.. + /// + public static string InvalidCacheRoleName + { + get + { + return ResourceManager.GetString("InvalidCacheRoleName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid certificate format. Publish settings may be corrupted. Use Get-AzurePublishSettingsFile to download updated settings. + /// + public static string InvalidCertificate + { + get + { + return ResourceManager.GetString("InvalidCertificate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid certificate format.. + /// + public static string InvalidCertificateSingle + { + get + { + return ResourceManager.GetString("InvalidCertificateSingle", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided configuration path is invalid or doesn't exist. + /// + public static string InvalidConfigPath + { + get + { + return ResourceManager.GetString("InvalidConfigPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The country name is invalid, please use a valid two character country code, as described in ISO 3166-1 alpha-2.. + /// + public static string InvalidCountryNameMessage + { + get + { + return ResourceManager.GetString("InvalidCountryNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to set the default subscription.. + /// + public static string InvalidDefaultSubscription + { + get + { + return ResourceManager.GetString("InvalidDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deployment with {0} does not exist. + /// + public static string InvalidDeployment + { + get + { + return ResourceManager.GetString("InvalidDeployment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The deployment slot name {0} is invalid. Slot name must be either "Staging" or "Production".. + /// + public static string InvalidDeploymentSlot + { + get + { + return ResourceManager.GetString("InvalidDeploymentSlot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "{0}" is an invalid DNS name for {1}. + /// + public static string InvalidDnsName + { + get + { + return ResourceManager.GetString("InvalidDnsName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid service endpoint.. + /// + public static string InvalidEndpoint + { + get + { + return ResourceManager.GetString("InvalidEndpoint", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided file in {0} must be have {1} extension. + /// + public static string InvalidFileExtension + { + get + { + return ResourceManager.GetString("InvalidFileExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File {0} has invalid characters. + /// + public static string InvalidFileName + { + get + { + return ResourceManager.GetString("InvalidFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must create your git publishing credentials using the Microsoft Azure portal. + ///Please follow these steps in the portal: + ///1. On the left side open "Web Sites" + ///2. Click on any website + ///3. Choose "Setup Git Publishing" or "Reset deployment credentials" + ///4. Back in the PowerShell window, rerun this command by typing "New-AzureWebSite {site name} -Git -PublishingUsername {username}. + /// + public static string InvalidGitCredentials + { + get + { + return ResourceManager.GetString("InvalidGitCredentials", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The value {0} provided is not a valid GUID. Please provide a valid GUID.. + /// + public static string InvalidGuid + { + get + { + return ResourceManager.GetString("InvalidGuid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The specified hostname does not exist. Please specify a valid hostname for the site.. + /// + public static string InvalidHostnameValidation + { + get + { + return ResourceManager.GetString("InvalidHostnameValidation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} instances must be greater than or equal 0 and less than or equal 20. + /// + public static string InvalidInstancesCount + { + get + { + return ResourceManager.GetString("InvalidInstancesCount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There was an error creating your webjob. Please make sure that the script is in the root folder of the zip file.. + /// + public static string InvalidJobFile + { + get + { + return ResourceManager.GetString("InvalidJobFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Could not download a valid runtime manifest, Please check your internet connection and try again.. + /// + public static string InvalidManifestError + { + get + { + return ResourceManager.GetString("InvalidManifestError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The account {0} was not found. Please specify a valid account name.. + /// + public static string InvalidMediaServicesAccount + { + get + { + return ResourceManager.GetString("InvalidMediaServicesAccount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided name "{0}" does not match the service bus namespace naming rules.. + /// + public static string InvalidNamespaceName + { + get + { + return ResourceManager.GetString("InvalidNamespaceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path must specify a valid path to an Azure profile.. + /// + public static string InvalidNewProfilePath + { + get + { + return ResourceManager.GetString("InvalidNewProfilePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Value cannot be null. Parameter name: '{0}'. + /// + public static string InvalidNullArgument + { + get + { + return ResourceManager.GetString("InvalidNullArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} is invalid or empty. + /// + public static string InvalidOrEmptyArgumentMessage + { + get + { + return ResourceManager.GetString("InvalidOrEmptyArgumentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided package path is invalid or doesn't exist. + /// + public static string InvalidPackagePath + { + get + { + return ResourceManager.GetString("InvalidPackagePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to '{0}' is an invalid parameter set name.. + /// + public static string InvalidParameterSetName + { + get + { + return ResourceManager.GetString("InvalidParameterSetName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} doesn't exist in {1} or you've not passed valid value for it. + /// + public static string InvalidPath + { + get + { + return ResourceManager.GetString("InvalidPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path {0} has invalid characters. + /// + public static string InvalidPathName + { + get + { + return ResourceManager.GetString("InvalidPathName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain one of the following sets of properties: {SubscriptionId, Certificate}, {SubscriptionId, Username, Password}, {SubscriptionId, ServicePrincipal, Password, Tenant}, {SubscriptionId, AccountId, Token}. + /// + public static string InvalidProfileProperties + { + get + { + return ResourceManager.GetString("InvalidProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided publish settings file {0} has invalid content. Please get valid by running cmdlet Get-AzurePublishSettingsFile. + /// + public static string InvalidPublishSettingsSchema + { + get + { + return ResourceManager.GetString("InvalidPublishSettingsSchema", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided role name "{0}" has invalid characters. + /// + public static string InvalidRoleNameMessage + { + get + { + return ResourceManager.GetString("InvalidRoleNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid name for the service root folder is required. + /// + public static string InvalidRootNameMessage + { + get + { + return ResourceManager.GetString("InvalidRootNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} is not a recognized runtime type. + /// + public static string InvalidRuntimeError + { + get + { + return ResourceManager.GetString("InvalidRuntimeError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid language is required. + /// + public static string InvalidScaffoldingLanguageArg + { + get + { + return ResourceManager.GetString("InvalidScaffoldingLanguageArg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No subscription is currently selected. Use Select-Subscription to activate a subscription.. + /// + public static string InvalidSelectedSubscription + { + get + { + return ResourceManager.GetString("InvalidSelectedSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided location "{0}" does not exist in the available locations use Get-AzureSBLocation for listing available locations.. + /// + public static string InvalidServiceBusLocation + { + get + { + return ResourceManager.GetString("InvalidServiceBusLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please provide a service name or run this command from inside a service project directory.. + /// + public static string InvalidServiceName + { + get + { + return ResourceManager.GetString("InvalidServiceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must provide valid value for {0}. + /// + public static string InvalidServiceSettingElement + { + get + { + return ResourceManager.GetString("InvalidServiceSettingElement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to settings.json is invalid or doesn't exist. + /// + public static string InvalidServiceSettingMessage + { + get + { + return ResourceManager.GetString("InvalidServiceSettingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named '{0}' cannot be found. Use Set-AzureSubscription to initialize the subscription data.. + /// + public static string InvalidSubscription + { + get + { + return ResourceManager.GetString("InvalidSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided subscription id {0} is not valid. + /// + public static string InvalidSubscriptionId + { + get + { + return ResourceManager.GetString("InvalidSubscriptionId", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Must specify a non-null subscription name.. + /// + public static string InvalidSubscriptionName + { + get + { + return ResourceManager.GetString("InvalidSubscriptionName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid subscription name is required. This can be provided using the -Subscription parameter or by setting the subscription via the Set-AzureSubscription cmdlet. + /// + public static string InvalidSubscriptionNameMessage + { + get + { + return ResourceManager.GetString("InvalidSubscriptionNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided subscriptions file {0} has invalid content.. + /// + public static string InvalidSubscriptionsDataSchema + { + get + { + return ResourceManager.GetString("InvalidSubscriptionsDataSchema", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} VM size should be ExtraSmall, Small, Medium, Large or ExtraLarge.. + /// + public static string InvalidVMSize + { + get + { + return ResourceManager.GetString("InvalidVMSize", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The web job file must have *.zip extension. + /// + public static string InvalidWebJobFile + { + get + { + return ResourceManager.GetString("InvalidWebJobFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Singleton option works for continuous jobs only.. + /// + public static string InvalidWebJobSingleton + { + get + { + return ResourceManager.GetString("InvalidWebJobSingleton", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The website {0} was not found. Please specify a valid website name.. + /// + public static string InvalidWebsite + { + get + { + return ResourceManager.GetString("InvalidWebsite", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No job for id: {0} was found.. + /// + public static string JobNotFound + { + get + { + return ResourceManager.GetString("JobNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to engines. + /// + public static string JsonEnginesSectionName + { + get + { + return ResourceManager.GetString("JsonEnginesSectionName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Scaffolding for this language is not yet supported. + /// + public static string LanguageScaffoldingIsNotSupported + { + get + { + return ResourceManager.GetString("LanguageScaffoldingIsNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Link already established. + /// + public static string LinkAlreadyEstablished + { + get + { + return ResourceManager.GetString("LinkAlreadyEstablished", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to local_package.csx. + /// + public static string LocalPackageFileName + { + get + { + return ResourceManager.GetString("LocalPackageFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceConfiguration.Local.cscfg. + /// + public static string LocalServiceConfigurationFileName + { + get + { + return ResourceManager.GetString("LocalServiceConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Looking for {0} deployment for {1} cloud service.... + /// + public static string LookingForDeploymentMessage + { + get + { + return ResourceManager.GetString("LookingForDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Looking for cloud service {0}.... + /// + public static string LookingForServiceMessage + { + get + { + return ResourceManager.GetString("LookingForServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure Long-Running Job. + /// + public static string LROJobName + { + get + { + return ResourceManager.GetString("LROJobName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet failed in background execution. The returned error was '{0}'. Please execute the cmdlet again. You may need to execute this cmdlet synchronously, by omitting the '-AsJob' parameter.. + /// + public static string LROTaskExceptionMessage + { + get + { + return ResourceManager.GetString("LROTaskExceptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to managementCertificate.pem. + /// + public static string ManagementCertificateFileName + { + get + { + return ResourceManager.GetString("ManagementCertificateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ?whr={0}. + /// + public static string ManagementPortalRealmFormat + { + get + { + return ResourceManager.GetString("ManagementPortalRealmFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to //baseuri. + /// + public static string ManifestBaseUriQuery + { + get + { + return ResourceManager.GetString("ManifestBaseUriQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to uri. + /// + public static string ManifestBlobUriKey + { + get + { + return ResourceManager.GetString("ManifestBlobUriKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to http://az413943.vo.msecnd.net/node/runtimemanifest_0.7.5.2.xml. + /// + public static string ManifestUri + { + get + { + return ResourceManager.GetString("ManifestUri", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'Certificate' of type 'X509Certificate2'.. + /// + public static string MissingCertificateInProfileProperties + { + get + { + return ResourceManager.GetString("MissingCertificateInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'Password' with an associated 'Username' or 'ServicePrincipal'.. + /// + public static string MissingPasswordInProfileProperties + { + get + { + return ResourceManager.GetString("MissingPasswordInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'SubscriptionId'.. + /// + public static string MissingSubscriptionInProfileProperties + { + get + { + return ResourceManager.GetString("MissingSubscriptionInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Multiple Add-Ons found holding name {0}. + /// + public static string MultipleAddOnsFoundMessage + { + get + { + return ResourceManager.GetString("MultipleAddOnsFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Multiple possible publishing users. Please go to the Portal and use the listed deployment user, or click 'set/reset deployment credentials' to set up a new user account, then reurn this cmdlet and specify PublishingUsername.. + /// + public static string MultiplePublishingUsernames + { + get + { + return ResourceManager.GetString("MultiplePublishingUsernames", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The first publish settings file "{0}" is used. If you want to use another file specify the file name.. + /// + public static string MultiplePublishSettingsFilesFoundMessage + { + get + { + return ResourceManager.GetString("MultiplePublishSettingsFilesFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.NamedCaches. + /// + public static string NamedCacheSettingName + { + get + { + return ResourceManager.GetString("NamedCacheSettingName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {"caches":[{"name":"default","policy":{"eviction":{"type":0},"expiration":{"defaultTTL":10,"isExpirable":true,"type":1},"serverNotification":{"isEnabled":false}},"secondaries":0}]}. + /// + public static string NamedCacheSettingValue + { + get + { + return ResourceManager.GetString("NamedCacheSettingValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A publishing username is required. Please specify one using the argument PublishingUsername.. + /// + public static string NeedPublishingUsernames + { + get + { + return ResourceManager.GetString("NeedPublishingUsernames", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to New Add-On Confirmation. + /// + public static string NewAddOnConformation + { + get + { + return ResourceManager.GetString("NewAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my + ///contact information with {2}.. + /// + public static string NewMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("NewMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen because the namespace name is already used or due to an incorrect location name. Use Get-AzureSBLocation cmdlet to list valid names.. + /// + public static string NewNamespaceErrorMessage + { + get + { + return ResourceManager.GetString("NewNamespaceErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of + ///use and privacy statement at {0} and (c) agree to sharing my contact information with {2}.. + /// + public static string NewNonMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("NewNonMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service has been created at {0}. + /// + public static string NewServiceCreatedMessage + { + get + { + return ResourceManager.GetString("NewServiceCreatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No. + /// + public static string No + { + get + { + return ResourceManager.GetString("No", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no access token cached for subscription {0}, user id {1}. Use the Add-AzureAccount cmdlet to log in again and get a token for this subscription.. + /// + public static string NoCachedToken + { + get + { + return ResourceManager.GetString("NoCachedToken", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The service does not have any cache worker roles, add one first by running cmdlet Add-AzureCacheWorkerRole.. + /// + public static string NoCacheWorkerRoles + { + get + { + return ResourceManager.GetString("NoCacheWorkerRoles", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No clouds available. + /// + public static string NoCloudsAvailable + { + get + { + return ResourceManager.GetString("NoCloudsAvailable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "There is no current context, please log in using Connect-AzAccount.". + /// + public static string NoCurrentContextForDataCmdlet + { + get + { + return ResourceManager.GetString("NoCurrentContextForDataCmdlet", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to nodejs. + /// + public static string NodeDirectory + { + get + { + return ResourceManager.GetString("NodeDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node. + /// + public static string NodeEngineKey + { + get + { + return ResourceManager.GetString("NodeEngineKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node.exe. + /// + public static string NodeExe + { + get + { + return ResourceManager.GetString("NodeExe", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no default subscription set, please set a default subscription by running Set-AzureSubscription -Default <subscription name>. + /// + public static string NoDefaultSubscriptionMessage + { + get + { + return ResourceManager.GetString("NoDefaultSubscriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft SDKs\Azure\Nodejs\Nov2011. + /// + public static string NodeModulesPath + { + get + { + return ResourceManager.GetString("NodeModulesPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to nodejs. + /// + public static string NodeProgramFilesFolderName + { + get + { + return ResourceManager.GetString("NodeProgramFilesFolderName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node. + /// + public static string NodeRuntimeValue + { + get + { + return ResourceManager.GetString("NodeRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\Node. + /// + public static string NodeScaffolding + { + get + { + return ResourceManager.GetString("NodeScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.Node. + /// + public static string NodeScaffoldingResources + { + get + { + return ResourceManager.GetString("NodeScaffoldingResources", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing Node version {0} in Azure for Role '{1}' (the Node version locally installed is: {2}). + /// + public static string NodeVersionWarningText + { + get + { + return ResourceManager.GetString("NodeVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No, I do not agree. + /// + public static string NoHint + { + get + { + return ResourceManager.GetString("NoHint", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please connect to internet before executing this cmdlet. + /// + public static string NoInternetConnection + { + get + { + return ResourceManager.GetString("NoInternetConnection", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to <NONE>. + /// + public static string None + { + get + { + return ResourceManager.GetString("None", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No publish settings files with extension *.publishsettings are found in the directory "{0}".. + /// + public static string NoPublishSettingsFilesFoundMessage + { + get + { + return ResourceManager.GetString("NoPublishSettingsFilesFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no subscription associated with account {0}.. + /// + public static string NoSubscriptionAddedMessage + { + get + { + return ResourceManager.GetString("NoSubscriptionAddedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No subscriptions are associated with the logged in account in Azure Service Management (RDFE). This means that the logged in user is not an administrator or co-administrator for any account.\r\nDid you mean to execute Connect-AzAccount?. + /// + public static string NoSubscriptionFoundForTenant + { + get + { + return ResourceManager.GetString("NoSubscriptionFoundForTenant", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to '{0}' must be a cache worker role. Verify that it has proper cache worker role configuration.. + /// + public static string NotCacheWorkerRole + { + get + { + return ResourceManager.GetString("NotCacheWorkerRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Certificate can't be null.. + /// + public static string NullCertificateMessage + { + get + { + return ResourceManager.GetString("NullCertificateMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} could not be null or empty. + /// + public static string NullObjectMessage + { + get + { + return ResourceManager.GetString("NullObjectMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to add a null RoleSettings to {0}. + /// + public static string NullRoleSettingsMessage + { + get + { + return ResourceManager.GetString("NullRoleSettingsMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to add new role to null service definition. + /// + public static string NullServiceDefinitionMessage + { + get + { + return ResourceManager.GetString("NullServiceDefinitionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The request offer '{0}' is not found.. + /// + public static string OfferNotFoundMessage + { + get + { + return ResourceManager.GetString("OfferNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Operation "{0}" failed on VM with ID: {1}. + /// + public static string OperationFailedErrorMessage + { + get + { + return ResourceManager.GetString("OperationFailedErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The REST operation failed with message '{0}' and error code '{1}'. + /// + public static string OperationFailedMessage + { + get + { + return ResourceManager.GetString("OperationFailedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Job Id {0} did not complete within expected time or it is in Failed/Canceled/Invalid state.. + /// + public static string OperationTimedOutOrError + { + get + { + return ResourceManager.GetString("OperationTimedOutOrError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to package. + /// + public static string Package + { + get + { + return ResourceManager.GetString("Package", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Package is created at service root path {0}.. + /// + public static string PackageCreated + { + get + { + return ResourceManager.GetString("PackageCreated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {{ + /// "author": "", + /// + /// "name": "{0}", + /// "version": "0.0.0", + /// "dependencies":{{}}, + /// "devDependencies":{{}}, + /// "optionalDependencies": {{}}, + /// "engines": {{ + /// "node": "*", + /// "iisnode": "*" + /// }} + /// + ///}} + ///. + /// + public static string PackageJsonDefaultFile + { + get + { + return ResourceManager.GetString("PackageJsonDefaultFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to package.json. + /// + public static string PackageJsonFileName + { + get + { + return ResourceManager.GetString("PackageJsonFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path {0} doesn't exist.. + /// + public static string PathDoesNotExist + { + get + { + return ResourceManager.GetString("PathDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path for {0} doesn't exist in {1}.. + /// + public static string PathDoesNotExistForElement + { + get + { + return ResourceManager.GetString("PathDoesNotExistForElement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the Peer Asn has to be provided.. + /// + public static string PeerAsnRequired + { + get + { + return ResourceManager.GetString("PeerAsnRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 5.4.0. + /// + public static string PHPDefaultRuntimeVersion + { + get + { + return ResourceManager.GetString("PHPDefaultRuntimeVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to php. + /// + public static string PhpRuntimeValue + { + get + { + return ResourceManager.GetString("PhpRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\PHP. + /// + public static string PHPScaffolding + { + get + { + return ResourceManager.GetString("PHPScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.PHP. + /// + public static string PHPScaffoldingResources + { + get + { + return ResourceManager.GetString("PHPScaffoldingResources", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing PHP version {0} for Role '{1}' (the PHP version locally installed is: {2}). + /// + public static string PHPVersionWarningText + { + get + { + return ResourceManager.GetString("PHPVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must create your first web site using the Microsoft Azure portal. + ///Please follow these steps in the portal: + ///1. At the bottom of the page, click on New > Web Site > Quick Create + ///2. Type {0} in the URL field + ///3. Click on "Create Web Site" + ///4. Once the site has been created, click on the site name + ///5. Click on "Set up Git publishing" or "Reset deployment credentials" and setup a publishing username and password. Use those credentials for all new websites you create.. + /// + public static string PortalInstructions + { + get + { + return ResourceManager.GetString("PortalInstructions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 6. Back in the console window, rerun this command by typing "New-AzureWebsite <site name> -Git". + /// + public static string PortalInstructionsGit + { + get + { + return ResourceManager.GetString("PortalInstructionsGit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The estimated generally available date is '{0}'.. + /// + public static string PreviewCmdletETAMessage { + get { + return ResourceManager.GetString("PreviewCmdletETAMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This cmdlet is in preview. Its behavior is subject to change based on customer feedback.. + /// + public static string PreviewCmdletMessage + { + get + { + return ResourceManager.GetString("PreviewCmdletMessage", resourceCulture); + } + } + + + /// + /// Looks up a localized string similar to A value for the Primary Peer Subnet has to be provided.. + /// + public static string PrimaryPeerSubnetRequired + { + get + { + return ResourceManager.GetString("PrimaryPeerSubnetRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Promotion code can be used only when updating to a new plan.. + /// + public static string PromotionCodeWithCurrentPlanMessage + { + get + { + return ResourceManager.GetString("PromotionCodeWithCurrentPlanMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service not published at user request.. + /// + public static string PublishAbortedAtUserRequest + { + get + { + return ResourceManager.GetString("PublishAbortedAtUserRequest", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Complete.. + /// + public static string PublishCompleteMessage + { + get + { + return ResourceManager.GetString("PublishCompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Connecting.... + /// + public static string PublishConnectingMessage + { + get + { + return ResourceManager.GetString("PublishConnectingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created Deployment ID: {0}.. + /// + public static string PublishCreatedDeploymentMessage + { + get + { + return ResourceManager.GetString("PublishCreatedDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created hosted service '{0}'.. + /// + public static string PublishCreatedServiceMessage + { + get + { + return ResourceManager.GetString("PublishCreatedServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created Website URL: {0}.. + /// + public static string PublishCreatedWebsiteMessage + { + get + { + return ResourceManager.GetString("PublishCreatedWebsiteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Creating.... + /// + public static string PublishCreatingServiceMessage + { + get + { + return ResourceManager.GetString("PublishCreatingServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Initializing.... + /// + public static string PublishInitializingMessage + { + get + { + return ResourceManager.GetString("PublishInitializingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to busy. + /// + public static string PublishInstanceStatusBusy + { + get + { + return ResourceManager.GetString("PublishInstanceStatusBusy", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to creating the virtual machine. + /// + public static string PublishInstanceStatusCreating + { + get + { + return ResourceManager.GetString("PublishInstanceStatusCreating", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Instance {0} of role {1} is {2}.. + /// + public static string PublishInstanceStatusMessage + { + get + { + return ResourceManager.GetString("PublishInstanceStatusMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ready. + /// + public static string PublishInstanceStatusReady + { + get + { + return ResourceManager.GetString("PublishInstanceStatusReady", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Preparing deployment for {0} with Subscription ID: {1}.... + /// + public static string PublishPreparingDeploymentMessage + { + get + { + return ResourceManager.GetString("PublishPreparingDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Publishing {0} to Microsoft Azure. This may take several minutes.... + /// + public static string PublishServiceStartMessage + { + get + { + return ResourceManager.GetString("PublishServiceStartMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to publish settings. + /// + public static string PublishSettings + { + get + { + return ResourceManager.GetString("PublishSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure. + /// + public static string PublishSettingsElementName + { + get + { + return ResourceManager.GetString("PublishSettingsElementName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to .PublishSettings. + /// + public static string PublishSettingsFileExtention + { + get + { + return ResourceManager.GetString("PublishSettingsFileExtention", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to publishSettings.xml. + /// + public static string PublishSettingsFileName + { + get + { + return ResourceManager.GetString("PublishSettingsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to &whr={0}. + /// + public static string PublishSettingsFileRealmFormat + { + get + { + return ResourceManager.GetString("PublishSettingsFileRealmFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Publish settings imported. + /// + public static string PublishSettingsSetSuccessfully + { + get + { + return ResourceManager.GetString("PublishSettingsSetSuccessfully", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_PUBLISHINGPROFILE_URL. + /// + public static string PublishSettingsUrlEnv + { + get + { + return ResourceManager.GetString("PublishSettingsUrlEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Starting.... + /// + public static string PublishStartingMessage + { + get + { + return ResourceManager.GetString("PublishStartingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Upgrading.... + /// + public static string PublishUpgradingMessage + { + get + { + return ResourceManager.GetString("PublishUpgradingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Uploading Package to storage service {0}.... + /// + public static string PublishUploadingPackageMessage + { + get + { + return ResourceManager.GetString("PublishUploadingPackageMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Verifying storage account '{0}'.... + /// + public static string PublishVerifyingStorageMessage + { + get + { + return ResourceManager.GetString("PublishVerifyingStorageMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path '{0}' not found.. + /// + public static string PublishVMDscExtensionAdditionalContentPathNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionAdditionalContentPathNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration published to {0}. + /// + public static string PublishVMDscExtensionArchiveUploadedMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionArchiveUploadedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Copy '{0}' to '{1}'.. + /// + public static string PublishVMDscExtensionCopyFileVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCopyFileVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Copy the module '{0}' to '{1}'.. + /// + public static string PublishVMDscExtensionCopyModuleVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCopyModuleVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid configuration file: {0}. + ///The file needs to be a PowerShell script (.ps1 or .psm1).. + /// + public static string PublishVMDscExtensionCreateArchiveConfigFileInvalidExtension + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCreateArchiveConfigFileInvalidExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleted '{0}'. + /// + public static string PublishVMDscExtensionDeletedFileMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDeletedFileMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot delete '{0}': {1}. + /// + public static string PublishVMDscExtensionDeleteErrorMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDeleteErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path '{0}' not found.. + /// + public static string PublishVMDscExtensionDirectoryNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDirectoryNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot get module for DscResource '{0}'. Possible solutions: + ///1) Specify -ModuleName for Import-DscResource in your configuration. + ///2) Unblock module that contains resource. + ///3) Move Import-DscResource inside Node block. + ///. + /// + public static string PublishVMDscExtensionGetDscResourceFailed + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionGetDscResourceFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to List of required modules: [{0}].. + /// + public static string PublishVMDscExtensionRequiredModulesVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionRequiredModulesVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Your current PowerShell version {1} is less then required by this cmdlet {0}. Consider download and install latest PowerShell version.. + /// + public static string PublishVMDscExtensionRequiredPsVersion + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionRequiredPsVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration script '{0}' contained parse errors: + ///{1}. + /// + public static string PublishVMDscExtensionStorageParserErrors + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionStorageParserErrors", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Temp folder '{0}' created.. + /// + public static string PublishVMDscExtensionTempFolderVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionTempFolderVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid configuration file: {0}. + ///The file needs to be a PowerShell script (.ps1 or .psm1) or a ZIP archive (.zip).. + /// + public static string PublishVMDscExtensionUploadArchiveConfigFileInvalidExtension + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionUploadArchiveConfigFileInvalidExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration file '{0}' not found.. + /// + public static string PublishVMDscExtensionUploadArchiveConfigFileNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionUploadArchiveConfigFileNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure PowerShell collects usage data in order to improve your experience. + ///The data is anonymous and does not include commandline argument values. + ///The data is collected by Microsoft. + /// + ///Use the Disable-AzureDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Azure module. To disable data collection: PS > Disable-AzureDataCollection. + ///Use the Enable-AzureDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Azure module. To enable data collection: PS > Enab [rest of string was truncated]";. + /// + public static string RDFEDataCollectionMessage + { + get + { + return ResourceManager.GetString("RDFEDataCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Replace current deployment with '{0}' Id ?. + /// + public static string RedeployCommit + { + get + { + return ResourceManager.GetString("RedeployCommit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to regenerate key?. + /// + public static string RegenerateKeyWarning + { + get + { + return ResourceManager.GetString("RegenerateKeyWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Generate new key.. + /// + public static string RegenerateKeyWhatIfMessage + { + get + { + return ResourceManager.GetString("RegenerateKeyWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove account '{0}'?. + /// + public static string RemoveAccountConfirmation + { + get + { + return ResourceManager.GetString("RemoveAccountConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing account. + /// + public static string RemoveAccountMessage + { + get + { + return ResourceManager.GetString("RemoveAccountMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove Add-On Confirmation. + /// + public static string RemoveAddOnConformation + { + get + { + return ResourceManager.GetString("RemoveAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to If you delete this add-on, your data may be deleted and the operation may not be undone. You may have to purchase it again from the Microsoft Azure Store to use it. The price of the add-on may not be refunded. Are you sure you want to delete this add-on? Enter “Yes” to confirm.. + /// + public static string RemoveAddOnMessage + { + get + { + return ResourceManager.GetString("RemoveAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureBGPPeering Operation failed.. + /// + public static string RemoveAzureBGPPeeringFailed + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Bgp Peering. + /// + public static string RemoveAzureBGPPeeringMessage + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Bgp Peering with Service Key {0}.. + /// + public static string RemoveAzureBGPPeeringSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Bgp Peering with service key '{0}'?. + /// + public static string RemoveAzureBGPPeeringWarning + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Dedicated Circuit with service key '{0}'?. + /// + public static string RemoveAzureDedicatdCircuitWarning + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatdCircuitWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureDedicatedCircuit Operation failed.. + /// + public static string RemoveAzureDedicatedCircuitFailed + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureDedicatedCircuitLink Operation failed.. + /// + public static string RemoveAzureDedicatedCircuitLinkFailed + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Dedicated Circui Link. + /// + public static string RemoveAzureDedicatedCircuitLinkMessage + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Dedicated Circuit Link with Service Key {0} and Vnet Name {1}. + /// + public static string RemoveAzureDedicatedCircuitLinkSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Dedicated Circuit Link with service key '{0}' and virtual network name '{1}'?. + /// + public static string RemoveAzureDedicatedCircuitLinkWarning + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Dedicated Circuit. + /// + public static string RemoveAzureDedicatedCircuitMessage + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Dedicated Circuit with Service Key {0}.. + /// + public static string RemoveAzureDedicatedCircuitSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing cloud service {0}.... + /// + public static string RemoveAzureServiceWaitMessage + { + get + { + return ResourceManager.GetString("RemoveAzureServiceWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The default subscription is being removed. Use Select-AzureSubscription -Default <subscriptionName> to select a new default subscription.. + /// + public static string RemoveDefaultSubscription + { + get + { + return ResourceManager.GetString("RemoveDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing {0} deployment for {1} service. + /// + public static string RemoveDeploymentWaitMessage + { + get + { + return ResourceManager.GetString("RemoveDeploymentWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing an environment will remove all associated subscriptions and accounts. Are you sure you want to remove an environment '{0}'?. + /// + public static string RemoveEnvironmentConfirmation + { + get + { + return ResourceManager.GetString("RemoveEnvironmentConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing environment. + /// + public static string RemoveEnvironmentMessage + { + get + { + return ResourceManager.GetString("RemoveEnvironmentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing job collection. + /// + public static string RemoveJobCollectionMessage + { + get + { + return ResourceManager.GetString("RemoveJobCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the job collection "{0}". + /// + public static string RemoveJobCollectionWarning + { + get + { + return ResourceManager.GetString("RemoveJobCollectionWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing job. + /// + public static string RemoveJobMessage + { + get + { + return ResourceManager.GetString("RemoveJobMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the job "{0}". + /// + public static string RemoveJobWarning + { + get + { + return ResourceManager.GetString("RemoveJobWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the account?. + /// + public static string RemoveMediaAccountWarning + { + get + { + return ResourceManager.GetString("RemoveMediaAccountWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account removed.. + /// + public static string RemoveMediaAccountWhatIfMessage + { + get + { + return ResourceManager.GetString("RemoveMediaAccountWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen because the namespace does not exist or it does not exist under your subscription.. + /// + public static string RemoveNamespaceErrorMessage + { + get + { + return ResourceManager.GetString("RemoveNamespaceErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing old package {0}.... + /// + public static string RemovePackage + { + get + { + return ResourceManager.GetString("RemovePackage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing the Azure profile will remove all associated environments, subscriptions, and accounts. Are you sure you want to remove the Azure profile?. + /// + public static string RemoveProfileConfirmation + { + get + { + return ResourceManager.GetString("RemoveProfileConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing the Azure profile. + /// + public static string RemoveProfileMessage + { + get + { + return ResourceManager.GetString("RemoveProfileMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to delete the namespace '{0}'?. + /// + public static string RemoveServiceBusNamespaceConfirmation + { + get + { + return ResourceManager.GetString("RemoveServiceBusNamespaceConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove cloud service?. + /// + public static string RemoveServiceWarning + { + get + { + return ResourceManager.GetString("RemoveServiceWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove cloud service and all it's deployments. + /// + public static string RemoveServiceWhatIfMessage + { + get + { + return ResourceManager.GetString("RemoveServiceWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove subscription '{0}'?. + /// + public static string RemoveSubscriptionConfirmation + { + get + { + return ResourceManager.GetString("RemoveSubscriptionConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing subscription. + /// + public static string RemoveSubscriptionMessage + { + get + { + return ResourceManager.GetString("RemoveSubscriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The endpoint {0} cannot be removed from profile {1} because it's not in the profile.. + /// + public static string RemoveTrafficManagerEndpointMissing + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerEndpointMissing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureTrafficManagerProfile Operation failed.. + /// + public static string RemoveTrafficManagerProfileFailed + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Traffic Manager profile with name {0}.. + /// + public static string RemoveTrafficManagerProfileSucceeded + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Traffic Manager profile "{0}"?. + /// + public static string RemoveTrafficManagerProfileWarning + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to delete the VM '{0}'?. + /// + public static string RemoveVMConfirmationMessage + { + get + { + return ResourceManager.GetString("RemoveVMConfirmationMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleting VM.. + /// + public static string RemoveVMMessage + { + get + { + return ResourceManager.GetString("RemoveVMMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing WebJob.... + /// + public static string RemoveWebJobMessage + { + get + { + return ResourceManager.GetString("RemoveWebJobMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove job '{0}'?. + /// + public static string RemoveWebJobWarning + { + get + { + return ResourceManager.GetString("RemoveWebJobWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing website. + /// + public static string RemoveWebsiteMessage + { + get + { + return ResourceManager.GetString("RemoveWebsiteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the website "{0}". + /// + public static string RemoveWebsiteWarning + { + get + { + return ResourceManager.GetString("RemoveWebsiteWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing public environment is not supported.. + /// + public static string RemovingDefaultEnvironmentsNotSupported + { + get + { + return ResourceManager.GetString("RemovingDefaultEnvironmentsNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleting namespace. + /// + public static string RemovingNamespaceMessage + { + get + { + return ResourceManager.GetString("RemovingNamespaceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Repository is not setup. You need to pass a valid site name.. + /// + public static string RepositoryNotSetup + { + get + { + return ResourceManager.GetString("RepositoryNotSetup", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Reserved IP with the Name:'{0}' will no longer be in use after the deployment is deleted, and it is still reserved for later use.. + /// + public static string ReservedIPNameNoLongerInUseButStillBeingReserved + { + get + { + return ResourceManager.GetString("ReservedIPNameNoLongerInUseButStillBeingReserved", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resource with ID : {0} does not exist.. + /// + public static string ResourceNotFound + { + get + { + return ResourceManager.GetString("ResourceNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Restart. + /// + public static string Restart + { + get + { + return ResourceManager.GetString("Restart", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resume. + /// + public static string Resume + { + get + { + return ResourceManager.GetString("Resume", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /role:{0};"{1}/{0}" . + /// + public static string RoleArgTemplate + { + get + { + return ResourceManager.GetString("RoleArgTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to bin. + /// + public static string RoleBinFolderName + { + get + { + return ResourceManager.GetString("RoleBinFolderName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} is {1}. + /// + public static string RoleInstanceWaitMsg + { + get + { + return ResourceManager.GetString("RoleInstanceWaitMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 20. + /// + public static string RoleMaxInstances + { + get + { + return ResourceManager.GetString("RoleMaxInstances", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to role name. + /// + public static string RoleName + { + get + { + return ResourceManager.GetString("RoleName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided role name {0} doesn't exist. + /// + public static string RoleNotFoundMessage + { + get + { + return ResourceManager.GetString("RoleNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RoleSettings.xml. + /// + public static string RoleSettingsTemplateFileName + { + get + { + return ResourceManager.GetString("RoleSettingsTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role type {0} doesn't exist. + /// + public static string RoleTypeDoesNotExist + { + get + { + return ResourceManager.GetString("RoleTypeDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to public static Dictionary<string, Location> ReverseLocations { get; private set; }. + /// + public static string RuntimeDeploymentLocationError + { + get + { + return ResourceManager.GetString("RuntimeDeploymentLocationError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Preparing runtime deployment for service '{0}'. + /// + public static string RuntimeDeploymentStart + { + get + { + return ResourceManager.GetString("RuntimeDeploymentStart", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WARNING Runtime Mismatch: Are you sure that you want to publish service '{0}' using an Azure runtime version that does not match your local runtime version?. + /// + public static string RuntimeMismatchWarning + { + get + { + return ResourceManager.GetString("RuntimeMismatchWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEOVERRIDEURL. + /// + public static string RuntimeOverrideKey + { + get + { + return ResourceManager.GetString("RuntimeOverrideKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /runtimemanifest/runtimes/runtime. + /// + public static string RuntimeQuery + { + get + { + return ResourceManager.GetString("RuntimeQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEID. + /// + public static string RuntimeTypeKey + { + get + { + return ResourceManager.GetString("RuntimeTypeKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEURL. + /// + public static string RuntimeUrlKey + { + get + { + return ResourceManager.GetString("RuntimeUrlKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEVERSIONPRIMARYKEY. + /// + public static string RuntimeVersionPrimaryKey + { + get + { + return ResourceManager.GetString("RuntimeVersionPrimaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to scaffold.xml. + /// + public static string ScaffoldXml + { + get + { + return ResourceManager.GetString("ScaffoldXml", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid location entered. Pick one of the locations from Get-AzureSchedulerLocation. + /// + public static string SchedulerInvalidLocation + { + get + { + return ResourceManager.GetString("SchedulerInvalidLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the Secondary Peer Subnet has to be provided.. + /// + public static string SecondaryPeerSubnetRequired + { + get + { + return ResourceManager.GetString("SecondaryPeerSubnetRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} already exists on disk in location {1}. + /// + public static string ServiceAlreadyExistsOnDisk + { + get + { + return ResourceManager.GetString("ServiceAlreadyExistsOnDisk", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No ServiceBus authorization rule with the given characteristics was found. + /// + public static string ServiceBusAuthorizationRuleNotFound + { + get + { + return ResourceManager.GetString("ServiceBusAuthorizationRuleNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The service bus entity '{0}' is not found.. + /// + public static string ServiceBusEntityTypeNotFound + { + get + { + return ResourceManager.GetString("ServiceBusEntityTypeNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen due to an incorrect/missing namespace. + /// + public static string ServiceBusNamespaceMissingMessage + { + get + { + return ResourceManager.GetString("ServiceBusNamespaceMissingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service configuration. + /// + public static string ServiceConfiguration + { + get + { + return ResourceManager.GetString("ServiceConfiguration", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service definition. + /// + public static string ServiceDefinition + { + get + { + return ResourceManager.GetString("ServiceDefinition", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceDefinition.csdef. + /// + public static string ServiceDefinitionFileName + { + get + { + return ResourceManager.GetString("ServiceDefinitionFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0}Deploy. + /// + public static string ServiceDeploymentName + { + get + { + return ResourceManager.GetString("ServiceDeploymentName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The specified cloud service "{0}" does not exist.. + /// + public static string ServiceDoesNotExist + { + get + { + return ResourceManager.GetString("ServiceDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} slot for service {1} is in {2} state, please wait until it finish and update it's status. + /// + public static string ServiceIsInTransitionState + { + get + { + return ResourceManager.GetString("ServiceIsInTransitionState", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "An exception occurred when calling the ServiceManagement API. HTTP Status Code: {0}. Service Management Error Code: {1}. Message: {2}. Operation Tracking ID: {3}.". + /// + public static string ServiceManagementClientExceptionStringFormat + { + get + { + return ResourceManager.GetString("ServiceManagementClientExceptionStringFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Begin Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionBeginOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionBeginOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Completed Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionCompletedOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionCompletedOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Begin Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionInOCSBeginOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionInOCSBeginOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Completed Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionInOCSCompletedOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionInOCSCompletedOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service name. + /// + public static string ServiceName + { + get + { + return ResourceManager.GetString("ServiceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided service name {0} already exists, please pick another name. + /// + public static string ServiceNameExists + { + get + { + return ResourceManager.GetString("ServiceNameExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please provide name for the hosted service. + /// + public static string ServiceNameMissingMessage + { + get + { + return ResourceManager.GetString("ServiceNameMissingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service parent directory. + /// + public static string ServiceParentDirectory + { + get + { + return ResourceManager.GetString("ServiceParentDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} removed successfully. + /// + public static string ServiceRemovedMessage + { + get + { + return ResourceManager.GetString("ServiceRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service directory. + /// + public static string ServiceRoot + { + get + { + return ResourceManager.GetString("ServiceRoot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service settings. + /// + public static string ServiceSettings + { + get + { + return ResourceManager.GetString("ServiceSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The storage account name '{0}' is invalid. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only.. + /// + public static string ServiceSettings_ValidateStorageAccountName_InvalidName + { + get + { + return ResourceManager.GetString("ServiceSettings_ValidateStorageAccountName_InvalidName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The {0} slot for cloud service {1} doesn't exist.. + /// + public static string ServiceSlotDoesNotExist + { + get + { + return ResourceManager.GetString("ServiceSlotDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} slot for service {1} is {2}. + /// + public static string ServiceStatusChanged + { + get + { + return ResourceManager.GetString("ServiceStatusChanged", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Set Add-On Confirmation. + /// + public static string SetAddOnConformation + { + get + { + return ResourceManager.GetString("SetAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Profile {0} does not contain endpoint {1}. Adding it.. + /// + public static string SetInexistentTrafficManagerEndpointMessage + { + get + { + return ResourceManager.GetString("SetInexistentTrafficManagerEndpointMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note - You will be charged the amount for the new plan, without being refunded for time remaining + ///in the existing plan. + ///By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my + ///contact information with {2}.. + /// + public static string SetMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("SetMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note - You will be charged the amount for the new plan, without being refunded for time remaining + ///in the existing plan. + ///By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of + ///use and privacy statement at <url> and (c) agree to sharing my contact information with {2}.. + /// + public static string SetNonMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("SetNonMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} instances are set to {1}. + /// + public static string SetRoleInstancesMessage + { + get + { + return ResourceManager.GetString("SetRoleInstancesMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {"Slot":"","Location":"","Subscription":"","StorageAccountName":""}. + /// + public static string SettingsFileEmptyContent + { + get + { + return ResourceManager.GetString("SettingsFileEmptyContent", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to deploymentSettings.json. + /// + public static string SettingsFileName + { + get + { + return ResourceManager.GetString("SettingsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Insufficient parameters passed to create a new endpoint.. + /// + public static string SetTrafficManagerEndpointNeedsParameters + { + get + { + return ResourceManager.GetString("SetTrafficManagerEndpointNeedsParameters", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Ambiguous operation: the profile name specified doesn't match the name of the profile object.. + /// + public static string SetTrafficManagerProfileAmbiguous + { + get + { + return ResourceManager.GetString("SetTrafficManagerProfileAmbiguous", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and include the 'Force' parameter, if available, to avoid unnecessary prompts.. + /// + public static string ShouldContinueFail + { + get + { + return ResourceManager.GetString("ShouldContinueFail", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Confirm. + /// + public static string ShouldProcessCaption + { + get + { + return ResourceManager.GetString("ShouldProcessCaption", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and omit the 'Confirm' parameter when using the 'AsJob' parameter.. + /// + public static string ShouldProcessFailConfirm + { + get + { + return ResourceManager.GetString("ShouldProcessFailConfirm", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please increase the user $ConfirmPreference setting, or include turn off confirmation using '-Confirm:$false' when using the 'AsJob' parameter and execute the cmdet again.. + /// + public static string ShouldProcessFailImpact + { + get + { + return ResourceManager.GetString("ShouldProcessFailImpact", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and omit the 'WhatIf' parameter when using the 'AsJob' parameter.. + /// + public static string ShouldProcessFailWhatIf + { + get + { + return ResourceManager.GetString("ShouldProcessFailWhatIf", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Shutdown. + /// + public static string Shutdown + { + get + { + return ResourceManager.GetString("Shutdown", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /sites:{0};{1};"{2}/{0}" . + /// + public static string SitesArgTemplate + { + get + { + return ResourceManager.GetString("SitesArgTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1000. + /// + public static string StandardRetryDelayInMs + { + get + { + return ResourceManager.GetString("StandardRetryDelayInMs", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Start. + /// + public static string Start + { + get + { + return ResourceManager.GetString("Start", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Started. + /// + public static string StartedEmulator + { + get + { + return ResourceManager.GetString("StartedEmulator", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Starting Emulator.... + /// + public static string StartingEmulator + { + get + { + return ResourceManager.GetString("StartingEmulator", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to start. + /// + public static string StartStorageEmulatorCommandArgument + { + get + { + return ResourceManager.GetString("StartStorageEmulatorCommandArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stop. + /// + public static string Stop + { + get + { + return ResourceManager.GetString("Stop", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stopping emulator.... + /// + public static string StopEmulatorMessage + { + get + { + return ResourceManager.GetString("StopEmulatorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stopped. + /// + public static string StoppedEmulatorMessage + { + get + { + return ResourceManager.GetString("StoppedEmulatorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to stop. + /// + public static string StopStorageEmulatorCommandArgument + { + get + { + return ResourceManager.GetString("StopStorageEmulatorCommandArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account Name:. + /// + public static string StorageAccountName + { + get + { + return ResourceManager.GetString("StorageAccountName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find storage account '{0}' please type the name of an existing storage account.. + /// + public static string StorageAccountNotFound + { + get + { + return ResourceManager.GetString("StorageAccountNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AzureStorageEmulator.exe. + /// + public static string StorageEmulatorExe + { + get + { + return ResourceManager.GetString("StorageEmulatorExe", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to InstallPath. + /// + public static string StorageEmulatorInstallPathRegistryKeyValue + { + get + { + return ResourceManager.GetString("StorageEmulatorInstallPathRegistryKeyValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to SOFTWARE\Microsoft\Windows Azure Storage Emulator. + /// + public static string StorageEmulatorRegistryKey + { + get + { + return ResourceManager.GetString("StorageEmulatorRegistryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Primary Key:. + /// + public static string StoragePrimaryKey + { + get + { + return ResourceManager.GetString("StoragePrimaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Secondary Key:. + /// + public static string StorageSecondaryKey + { + get + { + return ResourceManager.GetString("StorageSecondaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named {0} already exists.. + /// + public static string SubscriptionAlreadyExists + { + get + { + return ResourceManager.GetString("SubscriptionAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The SubscriptionDataFile parameter is deprecated. This parameter will be removed in a future release. See https://github.com/Azure/azure-powershell/wiki/Proposed-Design-Stateless-Azure-Profile for a description of the upcoming mechanism for providing alternate sources of subscription information.. + /// + public static string SubscriptionDataFileDeprecated + { + get + { + return ResourceManager.GetString("SubscriptionDataFileDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to DefaultSubscriptionData.xml. + /// + public static string SubscriptionDataFileName + { + get + { + return ResourceManager.GetString("SubscriptionDataFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription data file {0} does not exist.. + /// + public static string SubscriptionDataFileNotFound + { + get + { + return ResourceManager.GetString("SubscriptionDataFileNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription id {0} doesn't exist.. + /// + public static string SubscriptionIdNotFoundMessage + { + get + { + return ResourceManager.GetString("SubscriptionIdNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription must not be null. + /// + public static string SubscriptionMustNotBeNull + { + get + { + return ResourceManager.GetString("SubscriptionMustNotBeNull", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription name needs to be specified.. + /// + public static string SubscriptionNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("SubscriptionNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription name {0} doesn't exist.. + /// + public static string SubscriptionNameNotFoundMessage + { + get + { + return ResourceManager.GetString("SubscriptionNameNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription needs to be specified.. + /// + public static string SubscriptionNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("SubscriptionNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Suspend. + /// + public static string Suspend + { + get + { + return ResourceManager.GetString("Suspend", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Swapping website production slot .... + /// + public static string SwappingWebsite + { + get + { + return ResourceManager.GetString("SwappingWebsite", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to swap the website '{0}' production slot with slot '{1}'?. + /// + public static string SwapWebsiteSlotWarning + { + get + { + return ResourceManager.GetString("SwapWebsiteSlotWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The Switch-AzureMode cmdlet is deprecated and will be removed in a future release.. + /// + public static string SwitchAzureModeDeprecated + { + get + { + return ResourceManager.GetString("SwitchAzureModeDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Starting cmdlet execution, setting for cmdlet confirmation required: '{0}'. + /// + public static string TraceBeginLROJob + { + get + { + return ResourceManager.GetString("TraceBeginLROJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Blocking job for ShouldMethod '{0}'. + /// + public static string TraceBlockLROThread + { + get + { + return ResourceManager.GetString("TraceBlockLROThread", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Completing cmdlet execution in RunJob. + /// + public static string TraceEndLROJob + { + get + { + return ResourceManager.GetString("TraceEndLROJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: State change from '{0}' to '{1}' because '{2}'. + /// + public static string TraceHandleLROStateChange + { + get + { + return ResourceManager.GetString("TraceHandleLROStateChange", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Unblocking job due to stoppage or failure. + /// + public static string TraceHandlerCancelJob + { + get + { + return ResourceManager.GetString("TraceHandlerCancelJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Unblocking job that was previously blocked.. + /// + public static string TraceHandlerUnblockJob + { + get + { + return ResourceManager.GetString("TraceHandlerUnblockJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Error in cmdlet execution. + /// + public static string TraceLROJobException + { + get + { + return ResourceManager.GetString("TraceLROJobException", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Removing state changed event handler, exception '{0}'. + /// + public static string TraceRemoveLROEventHandler + { + get + { + return ResourceManager.GetString("TraceRemoveLROEventHandler", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: ShouldMethod '{0}' unblocked.. + /// + public static string TraceUnblockLROThread + { + get + { + return ResourceManager.GetString("TraceUnblockLROThread", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to decode string from base 64. Please make sure the string is correctly encoded: {0}.. + /// + public static string UnableToDecodeBase64String + { + get + { + return ResourceManager.GetString("UnableToDecodeBase64String", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to update mismatching Json structured: {0} {1}.. + /// + public static string UnableToPatchJson + { + get + { + return ResourceManager.GetString("UnableToPatchJson", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provider {0} is unknown.. + /// + public static string UnknownProviderMessage + { + get + { + return ResourceManager.GetString("UnknownProviderMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Update. + /// + public static string Update + { + get + { + return ResourceManager.GetString("Update", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Updated settings for subscription '{0}'. Current subscription is '{1}'.. + /// + public static string UpdatedSettings + { + get + { + return ResourceManager.GetString("UpdatedSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to User name is not valid.. + /// + public static string UserNameIsNotValid + { + get + { + return ResourceManager.GetString("UserNameIsNotValid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to User name needs to be specified.. + /// + public static string UserNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("UserNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the VLan Id has to be provided.. + /// + public static string VlanIdRequired + { + get + { + return ResourceManager.GetString("VlanIdRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please wait.... + /// + public static string WaitMessage + { + get + { + return ResourceManager.GetString("WaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The azure storage emulator is not installed, skip launching.... + /// + public static string WarningWhenStorageEmulatorIsMissing + { + get + { + return ResourceManager.GetString("WarningWhenStorageEmulatorIsMissing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Web.cloud.config. + /// + public static string WebCloudConfig + { + get + { + return ResourceManager.GetString("WebCloudConfig", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to web.config. + /// + public static string WebConfigTemplateFileName + { + get + { + return ResourceManager.GetString("WebConfigTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to MSDeploy. + /// + public static string WebDeployKeywordInWebSitePublishProfile + { + get + { + return ResourceManager.GetString("WebDeployKeywordInWebSitePublishProfile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot build the project successfully. Please see logs in {0}.. + /// + public static string WebProjectBuildFailTemplate + { + get + { + return ResourceManager.GetString("WebProjectBuildFailTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebRole. + /// + public static string WebRole + { + get + { + return ResourceManager.GetString("WebRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to setup_web.cmd > log.txt. + /// + public static string WebRoleStartupTaskCommandLine + { + get + { + return ResourceManager.GetString("WebRoleStartupTaskCommandLine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebRole.xml. + /// + public static string WebRoleTemplateFileName + { + get + { + return ResourceManager.GetString("WebRoleTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebSite with given name {0} already exists in the specified Subscription and Webspace.. + /// + public static string WebsiteAlreadyExists + { + get + { + return ResourceManager.GetString("WebsiteAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebSite with given name {0} already exists in the specified Subscription and Location.. + /// + public static string WebsiteAlreadyExistsReplacement + { + get + { + return ResourceManager.GetString("WebsiteAlreadyExistsReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Site {0} already has repository created for it.. + /// + public static string WebsiteRepositoryAlreadyExists + { + get + { + return ResourceManager.GetString("WebsiteRepositoryAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Workspaces/WebsiteExtension/Website/{0}/dashboard/. + /// + public static string WebsiteSufixUrl + { + get + { + return ResourceManager.GetString("WebsiteSufixUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://{0}/msdeploy.axd?site={1}. + /// + public static string WebSiteWebDeployUriTemplate + { + get + { + return ResourceManager.GetString("WebSiteWebDeployUriTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WorkerRole. + /// + public static string WorkerRole + { + get + { + return ResourceManager.GetString("WorkerRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to setup_worker.cmd > log.txt. + /// + public static string WorkerRoleStartupTaskCommandLine + { + get + { + return ResourceManager.GetString("WorkerRoleStartupTaskCommandLine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WorkerRole.xml. + /// + public static string WorkerRoleTemplateFileName + { + get + { + return ResourceManager.GetString("WorkerRoleTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to (x86). + /// + public static string x86InProgramFiles + { + get + { + return ResourceManager.GetString("x86InProgramFiles", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Yes. + /// + public static string Yes + { + get + { + return ResourceManager.GetString("Yes", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Yes, I agree. + /// + public static string YesHint + { + get + { + return ResourceManager.GetString("YesHint", resourceCulture); + } + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/Properties/Resources.resx b/src/Resources/DataBoundary.Autorest/generated/runtime/Properties/Resources.resx new file mode 100644 index 000000000000..a08a2e50172b --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/Properties/Resources.resx @@ -0,0 +1,1747 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The remote server returned an error: (401) Unauthorized. + + + Account "{0}" has been added. + + + To switch to a different subscription, please use Select-AzureSubscription. + + + Subscription "{0}" is selected as the default subscription. + + + To view all the subscriptions, please use Get-AzureSubscription. + + + Add-On {0} is created successfully. + + + Add-on name {0} is already used. + + + Add-On {0} not found. + + + Add-on {0} is removed successfully. + + + Add-On {0} is updated successfully. + + + Role has been created at {0}\{1}. + + + Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for Node.js by running ‘npm install azure’. + + + Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for PHP by running "pear WindowsAzure/WindowsAzure". + + + Unable to set role permissions. Please give the 'Network Service' user 'Read & execute' and 'Modify' permissions to the role folder, or run PowerShell as an Administrator + + + A role name '{0}' already exists + + + Windows Azure Powershell\ + + + https://manage.windowsazure.com + + + AZURE_PORTAL_URL + + + Azure SDK\{0}\ + + + Base Uri was empty. + WAPackIaaS + + + {0} begin processing without ParameterSet. + + + {0} begin processing with ParameterSet '{1}'. + + + Blob with the name {0} already exists in the account. + + + https://{0}.blob.core.windows.net/ + + + AZURE_BLOBSTORAGE_TEMPLATE + + + CACHERUNTIMEURL + + + cache + + + CacheRuntimeVersion + + + Installing caching version {0} for Role '{1}' (the caching version locally installed is: {2}) + + + Cannot find {0} with name {1}. + + + Deployment for service {0} with {1} slot doesn't exist + + + Can't find valid Microsoft Azure role in current directory {0} + + + service {0} configuration file (ServiceConfiguration.Cloud.cscfg) is either null or doesn't exist + + + Invalid service path! Cannot locate ServiceDefinition.csdef in current folder or parent folders. + + + The subscription named {0} with id {1} is not currently imported. You must import this subscription before it can be updated. + + + ManagementCertificate + + + certificate.pfx + + + Certificate imported into CurrentUser\My\{0} + + + Your account does not have access to the private key for certificate {0} + + + {0} {1} deployment for {2} service + + + Cloud service {0} is in {1} state. + + + Changing/Removing public environment '{0}' is not allowed. + + + Service {0} is set to value {1} + + + Choose which publish settings file to use: + + + Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel + + + 1 + + + cloud_package.cspkg + + + ServiceConfiguration.Cloud.cscfg + + + Add-ons for {0} + + + Communication could not be established. This could be due to an invalid subscription ID. Note that subscription IDs are case sensitive. + + + Complete + + + config.json + + + VirtualMachine creation failed. + WAPackIaaS + + + Creating the website failed. If this is the first website for this subscription, please create it using the management portal instead. + + + Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core + + + //blobcontainer[@datacenter='{0}'] + + + Setting: {0} as the default and current subscription. To view other subscriptions use Get-AzureSubscription + + + none + + + There are no hostnames which could be used for validation. + + + 8080 + + + 1000 + + + Auto + + + 80 + + + Delete + WAPackIaaS + + + The {0} slot for service {1} is already in {2} state + + + The deployment in {0} slot for service {1} is removed + + + Microsoft.WindowsAzure.Plugins.Caching.DiagnosticLevel + + + 1 + + + The key to add already exists in the dictionary. + + + The array index cannot be less than zero. + + + The supplied array does not have enough room to contain the copied elements. + + + The provided dns {0} doesn't exist + + + Microsoft Azure Certificate + + + Endpoint can't be retrieved for storage account + + + {0} end processing. + + + To use Active Directory authentication, you must configure the ActiveDirectoryEndpoint, ActiveDirectoryTenantId, and ActiveDirectorServiceEndpointResourceId for environment of '{0}'. You can configure these properties for this environment using the Set-AzureEnvironment cmdlet. + + + The environment '{0}' already exists. + + + environments.xml + + + Error creating VirtualMachine + WAPackIaaS + + + Unable to download available runtimes for location '{0}' + + + Error updating VirtualMachine + WAPackIaaS + + + Job Id {0} failed. Error: {1}, ExceptionDetails: {2} + WAPackIaaS + + + The HTTP request was forbidden with client authentication scheme 'Anonymous'. + + + This add-on requires you to purchase the first instance through the Microsoft Azure Portal. Subsequent purchases can be performed through PowerShell. + + + Operation Status: + + + Resources\Scaffolding\General + + + Getting all available Microsoft Azure Add-Ons, this may take few minutes... + + + Name{0}Primary Key{0}Seconday Key + + + Git not found. Please install git and place it in your command line path. + + + Could not find publish settings. Please run Import-AzurePublishSettingsFile. + + + iisnode.dll + + + iisnode + + + iisnode-dev\\release\\x64 + + + iisnode + + + Installing IISNode version {0} in Azure for WebRole '{1}' (the version locally installed is: {2}) + + + Internal Server Error + + + Cannot enable memcach protocol on a cache worker role {0}. + + + Invalid certificate format. + + + The provided configuration path is invalid or doesn't exist + + + The country name is invalid, please use a valid two character country code, as described in ISO 3166-1 alpha-2. + + + Deployment with {0} does not exist + + + The deployment slot name {0} is invalid. Slot name must be either "Staging" or "Production". + + + Invalid service endpoint. + + + File {0} has invalid characters + + + You must create your git publishing credentials using the Microsoft Azure portal. +Please follow these steps in the portal: +1. On the left side open "Web Sites" +2. Click on any website +3. Choose "Setup Git Publishing" or "Reset deployment credentials" +4. Back in the PowerShell window, rerun this command by typing "New-AzureWebSite {site name} -Git -PublishingUsername {username} + + + The value {0} provided is not a valid GUID. Please provide a valid GUID. + + + The specified hostname does not exist. Please specify a valid hostname for the site. + + + Role {0} instances must be greater than or equal 0 and less than or equal 20 + + + There was an error creating your webjob. Please make sure that the script is in the root folder of the zip file. + + + Could not download a valid runtime manifest, Please check your internet connection and try again. + + + The account {0} was not found. Please specify a valid account name. + + + The provided name "{0}" does not match the service bus namespace naming rules. + + + Value cannot be null. Parameter name: '{0}' + + + The provided package path is invalid or doesn't exist + + + '{0}' is an invalid parameter set name. + + + {0} doesn't exist in {1} or you've not passed valid value for it + + + Path {0} has invalid characters + + + The provided publish settings file {0} has invalid content. Please get valid by running cmdlet Get-AzurePublishSettingsFile + + + The provided role name "{0}" has invalid characters + + + A valid name for the service root folder is required + + + {0} is not a recognized runtime type + + + A valid language is required + + + No subscription is currently selected. Use Select-Subscription to activate a subscription. + + + The provided location "{0}" does not exist in the available locations use Get-AzureSBLocation for listing available locations. + + + Please provide a service name or run this command from inside a service project directory. + + + You must provide valid value for {0} + + + settings.json is invalid or doesn't exist + + + The subscription named '{0}' cannot be found. Use Set-AzureSubscription to initialize the subscription data. + + + The provided subscription id {0} is not valid + + + A valid subscription name is required. This can be provided using the -Subscription parameter or by setting the subscription via the Set-AzureSubscription cmdlet + + + The provided subscriptions file {0} has invalid content. + + + Role {0} VM size should be ExtraSmall, Small, Medium, Large or ExtraLarge. + + + The web job file must have *.zip extension + + + Singleton option works for continuous jobs only. + + + The website {0} was not found. Please specify a valid website name. + + + No job for id: {0} was found. + WAPackIaaS + + + engines + + + Scaffolding for this language is not yet supported + + + Link already established + + + local_package.csx + + + ServiceConfiguration.Local.cscfg + + + Looking for {0} deployment for {1} cloud service... + + + Looking for cloud service {0}... + + + managementCertificate.pem + + + ?whr={0} + + + //baseuri + + + uri + + + http://az413943.vo.msecnd.net/node/runtimemanifest_0.7.5.2.xml + + + Multiple Add-Ons found holding name {0} + + + Multiple possible publishing users. Please go to the Portal and use the listed deployment user, or click 'set/reset deployment credentials' to set up a new user account, then reurn this cmdlet and specify PublishingUsername. + + + The first publish settings file "{0}" is used. If you want to use another file specify the file name. + + + Microsoft.WindowsAzure.Plugins.Caching.NamedCaches + + + {"caches":[{"name":"default","policy":{"eviction":{"type":0},"expiration":{"defaultTTL":10,"isExpirable":true,"type":1},"serverNotification":{"isEnabled":false}},"secondaries":0}]} + + + A publishing username is required. Please specify one using the argument PublishingUsername. + + + New Add-On Confirmation + + + By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my +contact information with {2}. + + + Internal Server Error. This could happen because the namespace name is already used or due to an incorrect location name. Use Get-AzureSBLocation cmdlet to list valid names. + + + By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of +use and privacy statement at {0} and (c) agree to sharing my contact information with {2}. + + + Service has been created at {0} + + + No + + + There is no access token cached for subscription {0}, user id {1}. Use the Add-AzureAccount cmdlet to log in again and get a token for this subscription. + + + The service does not have any cache worker roles, add one first by running cmdlet Add-AzureCacheWorkerRole. + + + No clouds available + WAPackIaaS + + + nodejs + + + node + + + node.exe + + + There is no default subscription set, please set a default subscription by running Set-AzureSubscription -Default <subscription name> + + + Microsoft SDKs\Azure\Nodejs\Nov2011 + + + nodejs + + + node + + + Resources\Scaffolding\Node + + + Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.Node + + + Installing Node version {0} in Azure for Role '{1}' (the Node version locally installed is: {2}) + + + No, I do not agree + + + No publish settings files with extension *.publishsettings are found in the directory "{0}". + + + '{0}' must be a cache worker role. Verify that it has proper cache worker role configuration. + + + Certificate can't be null. + + + {0} could not be null or empty + + + Unable to add a null RoleSettings to {0} + + + Unable to add new role to null service definition + + + The request offer '{0}' is not found. + + + Operation "{0}" failed on VM with ID: {1} + WAPackIaaS + + + The REST operation failed with message '{0}' and error code '{1}' + + + Job Id {0} did not complete within expected time or it is in Failed/Canceled/Invalid state. + WAPackIaaS + + + package + + + Package is created at service root path {0}. + + + {{ + "author": "", + + "name": "{0}", + "version": "0.0.0", + "dependencies":{{}}, + "devDependencies":{{}}, + "optionalDependencies": {{}}, + "engines": {{ + "node": "*", + "iisnode": "*" + }} + +}} + + + + package.json + + + A value for the Peer Asn has to be provided. + + + 5.4.0 + + + php + + + Resources\Scaffolding\PHP + + + Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.PHP + + + Installing PHP version {0} for Role '{1}' (the PHP version locally installed is: {2}) + + + You must create your first web site using the Microsoft Azure portal. +Please follow these steps in the portal: +1. At the bottom of the page, click on New > Web Site > Quick Create +2. Type {0} in the URL field +3. Click on "Create Web Site" +4. Once the site has been created, click on the site name +5. Click on "Set up Git publishing" or "Reset deployment credentials" and setup a publishing username and password. Use those credentials for all new websites you create. + + + 6. Back in the console window, rerun this command by typing "New-AzureWebsite <site name> -Git" + + + A value for the Primary Peer Subnet has to be provided. + + + Promotion code can be used only when updating to a new plan. + + + Service not published at user request. + + + Complete. + + + Connecting... + + + Created Deployment ID: {0}. + + + Created hosted service '{0}'. + + + Created Website URL: {0}. + + + Creating... + + + Initializing... + + + busy + + + creating the virtual machine + + + Instance {0} of role {1} is {2}. + + + ready + + + Preparing deployment for {0} with Subscription ID: {1}... + + + Publishing {0} to Microsoft Azure. This may take several minutes... + + + publish settings + + + Azure + + + .PublishSettings + + + publishSettings.xml + + + Publish settings imported + + + AZURE_PUBLISHINGPROFILE_URL + + + Starting... + + + Upgrading... + + + Uploading Package to storage service {0}... + + + Verifying storage account '{0}'... + + + Replace current deployment with '{0}' Id ? + + + Are you sure you want to regenerate key? + + + Generate new key. + + + Are you sure you want to remove account '{0}'? + + + Removing account + + + Remove Add-On Confirmation + + + If you delete this add-on, your data may be deleted and the operation may not be undone. You may have to purchase it again from the Microsoft Azure Store to use it. The price of the add-on may not be refunded. Are you sure you want to delete this add-on? Enter “Yes” to confirm. + + + Remove-AzureBGPPeering Operation failed. + + + Removing Bgp Peering + + + Successfully removed Azure Bgp Peering with Service Key {0}. + + + Are you sure you want to remove the Bgp Peering with service key '{0}'? + + + Are you sure you want to remove the Dedicated Circuit with service key '{0}'? + + + Remove-AzureDedicatedCircuit Operation failed. + + + Remove-AzureDedicatedCircuitLink Operation failed. + + + Removing Dedicated Circui Link + + + Successfully removed Azure Dedicated Circuit Link with Service Key {0} and Vnet Name {1} + + + Are you sure you want to remove the Dedicated Circuit Link with service key '{0}' and virtual network name '{1}'? + + + Removing Dedicated Circuit + + + Successfully removed Azure Dedicated Circuit with Service Key {0}. + + + Removing cloud service {0}... + + + Removing {0} deployment for {1} service + + + Removing job collection + + + Are you sure you want to remove the job collection "{0}" + + + Removing job + + + Are you sure you want to remove the job "{0}" + + + Are you sure you want to remove the account? + + + Account removed. + + + Internal Server Error. This could happen because the namespace does not exist or it does not exist under your subscription. + + + Removing old package {0}... + + + Are you sure you want to delete the namespace '{0}'? + + + Are you sure you want to remove cloud service? + + + Remove cloud service and all it's deployments + + + Are you sure you want to remove subscription '{0}'? + + + Removing subscription + + + Are you sure you want to delete the VM '{0}'? + + + Deleting VM. + + + Removing WebJob... + + + Are you sure you want to remove job '{0}'? + + + Removing website + + + Are you sure you want to remove the website "{0}" + + + Deleting namespace + + + Repository is not setup. You need to pass a valid site name. + + + Reserved IP with the Name:'{0}' will no longer be in use after the deployment is deleted, and it is still reserved for later use. + + + Resource with ID : {0} does not exist. + WAPackIaaS + + + Restart + WAPackIaaS + + + Resume + WAPackIaaS + + + /role:{0};"{1}/{0}" + + + bin + + + Role {0} is {1} + + + 20 + + + role name + + + The provided role name {0} doesn't exist + + + RoleSettings.xml + + + Role type {0} doesn't exist + + + public static Dictionary<string, Location> ReverseLocations { get; private set; } + + + Preparing runtime deployment for service '{0}' + + + WARNING Runtime Mismatch: Are you sure that you want to publish service '{0}' using an Azure runtime version that does not match your local runtime version? + + + RUNTIMEOVERRIDEURL + + + /runtimemanifest/runtimes/runtime + + + RUNTIMEID + + + RUNTIMEURL + + + RUNTIMEVERSIONPRIMARYKEY + + + scaffold.xml + + + Invalid location entered. Pick one of the locations from Get-AzureSchedulerLocation + + + A value for the Secondary Peer Subnet has to be provided. + + + Service {0} already exists on disk in location {1} + + + No ServiceBus authorization rule with the given characteristics was found + + + The service bus entity '{0}' is not found. + + + Internal Server Error. This could happen due to an incorrect/missing namespace + + + service configuration + + + service definition + + + ServiceDefinition.csdef + + + {0}Deploy + + + The specified cloud service "{0}" does not exist. + + + {0} slot for service {1} is in {2} state, please wait until it finish and update it's status + + + Begin Operation: {0} + + + Completed Operation: {0} + + + Begin Operation: {0} + + + Completed Operation: {0} + + + service name + + + Please provide name for the hosted service + + + service parent directory + + + Service {0} removed successfully + + + service directory + + + service settings + + + The storage account name '{0}' is invalid. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. + + + The {0} slot for cloud service {1} doesn't exist. + + + {0} slot for service {1} is {2} + + + Set Add-On Confirmation + + + Note - You will be charged the amount for the new plan, without being refunded for time remaining +in the existing plan. +By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my +contact information with {2}. + + + Note - You will be charged the amount for the new plan, without being refunded for time remaining +in the existing plan. +By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of +use and privacy statement at <url> and (c) agree to sharing my contact information with {2}. + + + Role {0} instances are set to {1} + + + {"Slot":"","Location":"","Subscription":"","StorageAccountName":""} + + + deploymentSettings.json + + + Confirm + + + Shutdown + WAPackIaaS + + + /sites:{0};{1};"{2}/{0}" + + + 1000 + + + Start + WAPackIaaS + + + Started + + + Starting Emulator... + + + start + + + Stop + WAPackIaaS + + + Stopping emulator... + + + Stopped + + + stop + + + Account Name: + + + Cannot find storage account '{0}' please type the name of an existing storage account. + + + AzureStorageEmulator.exe + + + InstallPath + + + SOFTWARE\Microsoft\Windows Azure Storage Emulator + + + Primary Key: + + + Secondary Key: + + + The subscription named {0} already exists. + + + DefaultSubscriptionData.xml + + + The subscription data file {0} does not exist. + + + Subscription must not be null + WAPackIaaS + + + Suspend + WAPackIaaS + + + Swapping website production slot ... + + + Are you sure you want to swap the website '{0}' production slot with slot '{1}'? + + + The provider {0} is unknown. + + + Update + WAPackIaaS + + + Updated settings for subscription '{0}'. Current subscription is '{1}'. + + + A value for the VLan Id has to be provided. + + + Please wait... + + + The azure storage emulator is not installed, skip launching... + + + Web.cloud.config + + + web.config + + + MSDeploy + + + Cannot build the project successfully. Please see logs in {0}. + + + WebRole + + + setup_web.cmd > log.txt + + + WebRole.xml + + + WebSite with given name {0} already exists in the specified Subscription and Webspace. + + + WebSite with given name {0} already exists in the specified Subscription and Location. + + + Site {0} already has repository created for it. + + + Workspaces/WebsiteExtension/Website/{0}/dashboard/ + + + https://{0}/msdeploy.axd?site={1} + + + WorkerRole + + + setup_worker.cmd > log.txt + + + WorkerRole.xml + + + Yes + + + Yes, I agree + + + Remove-AzureTrafficManagerProfile Operation failed. + + + Successfully removed Traffic Manager profile with name {0}. + + + Are you sure you want to remove the Traffic Manager profile "{0}"? + + + Profile {0} already has an endpoint with name {1} + + + Profile {0} does not contain endpoint {1}. Adding it. + + + The endpoint {0} cannot be removed from profile {1} because it's not in the profile. + + + Insufficient parameters passed to create a new endpoint. + + + Ambiguous operation: the profile name specified doesn't match the name of the profile object. + + + <NONE> + + + "An exception occurred when calling the ServiceManagement API. HTTP Status Code: {0}. Service Management Error Code: {1}. Message: {2}. Operation Tracking ID: {3}." + {0} is the HTTP status code. {1} is the Service Management Error Code. {2} is the Service Management Error message. {3} is the operation tracking ID. + + + Unable to decode string from base 64. Please make sure the string is correctly encoded: {0}. + {0} is the string that is not in a valid base 64 format. + + + Skipping external tenant {0}, because you are using a guest or a foreign principal object identity. In order to access this tenant, please run Add-AzureAccount without "-Credential". + + + Removing an environment will remove all associated subscriptions and accounts. Are you sure you want to remove an environment '{0}'? + + + Removing environment + + + There is no subscription associated with account {0}. + + + Account id doesn't match one in subscription. + + + Environment name doesn't match one in subscription. + + + Removing the Azure profile will remove all associated environments, subscriptions, and accounts. Are you sure you want to remove the Azure profile? + + + Removing the Azure profile + + + The SubscriptionDataFile parameter is deprecated. This parameter will be removed in a future release. See https://github.com/Azure/azure-powershell/wiki/Proposed-Design-Stateless-Azure-Profile for a description of the upcoming mechanism for providing alternate sources of subscription information. + + + Account needs to be specified + + + No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to set the default subscription. + + + Path must specify a valid path to an Azure profile. + + + Property bag Hashtable must contain one of the following sets of properties: {SubscriptionId, Certificate}, {SubscriptionId, Username, Password}, {SubscriptionId, ServicePrincipal, Password, Tenant}, {SubscriptionId, AccountId, Token} + + + Property bag Hashtable must contain a 'Certificate' of type 'X509Certificate2'. + + + Property bag Hashtable must contain a 'Password' with an associated 'Username' or 'ServicePrincipal'. + + + Property bag Hashtable must contain a 'SubscriptionId'. + + + Selected profile must not be null. + + + The Switch-AzureMode cmdlet is deprecated and will be removed in a future release. + + + OperationID : '{0}' + + + Cannot get module for DscResource '{0}'. Possible solutions: +1) Specify -ModuleName for Import-DscResource in your configuration. +2) Unblock module that contains resource. +3) Move Import-DscResource inside Node block. + + 0 = name of DscResource + + + Your current PowerShell version {1} is less then required by this cmdlet {0}. Consider download and install latest PowerShell version. + {0} = minimal required PS version, {1} = current PS version + + + Parsing configuration script: {0} + {0} is the path to a script file + + + Configuration script '{0}' contained parse errors: +{1} + 0 = path to the configuration script, 1 = parser errors + + + List of required modules: [{0}]. + {0} = list of modules + + + Temp folder '{0}' created. + {0} = temp folder path + + + Copy '{0}' to '{1}'. + {0} = source, {1} = destination + + + Copy the module '{0}' to '{1}'. + {0} = source, {1} = destination + + + File '{0}' already exists. Use the -Force parameter to overwrite it. + {0} is the path to a file + + + Configuration file '{0}' not found. + 0 = path to the configuration file + + + Path '{0}' not found. + 0 = path to the additional content file/directory + + + Path '{0}' not found. + 0 = path to the additional content file/directory + + + Invalid configuration file: {0}. +The file needs to be a PowerShell script (.ps1 or .psm1) or a ZIP archive (.zip). + 0 = path to the configuration file + + + Invalid configuration file: {0}. +The file needs to be a PowerShell script (.ps1 or .psm1). + 0 = path to the configuration file + + + Create Archive + + + Upload '{0}' + {0} is the name of an storage blob + + + Storage Blob '{0}' already exists. Use the -Force parameter to overwrite it. + {0} is the name of an storage blob + + + Configuration published to {0} + {0} is an URI + + + Deleted '{0}' + {0} is the path of a file + + + Cannot delete '{0}': {1} + {0} is the path of a file, {1} is an error message + + + Cannot find the WadCfg end element in the config. + + + WadCfg start element in the config is not matching the end element. + + + Cannot find the WadCfg element in the config. + + + Cannot find configuration data file: {0} + + + The configuration data must be a .psd1 file + + + Cannot change built-in environment {0}. + + + Azure PowerShell collects usage data in order to improve your experience. +The data is anonymous and does not include commandline argument values. +The data is collected by Microsoft. + +Use the Disable-AzDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Az.Accounts module. To disable data collection: PS > Disable-AzDataCollection. +Use the Enable-AzDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Az.Accounts module. To enable data collection: PS > Enable-AzDataCollection. + + + Microsoft Azure PowerShell Data Collection Confirmation + + + You choose not to participate in Microsoft Azure PowerShell data collection. + + + This confirmation message will be dismissed in '{0}' second(s)... + + + You choose to participate in Microsoft Azure PowerShell data collection. + + + The setting profile has been saved to the following path '{0}'. + + + [Common.Authentication]: Authenticating for account {0} with single tenant {1}. + + + Changing public environment is not supported. + + + Environment name needs to be specified. + + + Environment needs to be specified. + + + The environment name '{0}' is not found. + + + File path is not valid. + + + Must specify a non-null subscription name. + + + The default subscription is being removed. Use Select-AzureSubscription -Default <subscriptionName> to select a new default subscription. + + + Removing public environment is not supported. + + + The subscription id {0} doesn't exist. + + + Subscription name needs to be specified. + + + The subscription name {0} doesn't exist. + + + Subscription needs to be specified. + + + User name is not valid. + + + User name needs to be specified. + + + "There is no current context, please log in using Connect-AzAccount." + + + No subscriptions are associated with the logged in account in Azure Service Management (RDFE). This means that the logged in user is not an administrator or co-administrator for any account.\r\nDid you mean to execute Connect-AzAccount? + + + No certificate was found in the certificate store with thumbprint {0} + + + Illegal characters in path. + + + Invalid certificate format. Publish settings may be corrupted. Use Get-AzurePublishSettingsFile to download updated settings + + + "{0}" is an invalid DNS name for {1} + + + The provided file in {0} must be have {1} extension + + + {0} is invalid or empty + + + Please connect to internet before executing this cmdlet + + + Path {0} doesn't exist. + + + Path for {0} doesn't exist in {1}. + + + &whr={0} + + + The provided service name {0} already exists, please pick another name + + + Unable to update mismatching Json structured: {0} {1}. + + + (x86) + + + Azure PowerShell collects usage data in order to improve your experience. +The data is anonymous and does not include commandline argument values. +The data is collected by Microsoft. + +Use the Disable-AzureDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Azure module. To disable data collection: PS > Disable-AzureDataCollection. +Use the Enable-AzureDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Azure module. To enable data collection: PS > Enable-AzureDataCollection. + + + Execution failed because a background thread could not prompt the user. + + + Azure Long-Running Job + + + The cmdlet failed in background execution. The returned error was '{0}'. Please execute the cmdlet again. You may need to execute this cmdlet synchronously, by omitting the '-AsJob' parameter. + 0(string): exception message in background task + + + Please execute the cmdlet again and include the 'Force' parameter, if available, to avoid unnecessary prompts. + + + Please execute the cmdlet again and omit the 'Confirm' parameter when using the 'AsJob' parameter. + + + Please increase the user $ConfirmPreference setting, or include turn off confirmation using '-Confirm:$false' when using the 'AsJob' parameter and execute the cmdet again. + + + Please execute the cmdlet again and omit the 'WhatIf' parameter when using the 'AsJob' parameter. + + + [AzureLongRunningJob]: Starting cmdlet execution, setting for cmdlet confirmation required: '{0}' + 0(bool): whether cmdlet confirmation is required + + + [AzureLongRunningJob]: Blocking job for ShouldMethod '{0}' + 0(string): method type + + + [AzureLongRunningJob]: Completing cmdlet execution in RunJob + + + [AzureLongRunningJob]: State change from '{0}' to '{1}' because '{2}' + 0(string): last state, 1(string): new state, 2(string): state change reason + + + [AzureLongRunningJob]: Unblocking job due to stoppage or failure + + + [AzureLongRunningJob]: Unblocking job that was previously blocked. + + + [AzureLongRunningJob]: Error in cmdlet execution + + + [AzureLongRunningJob]: Removing state changed event handler, exception '{0}' + 0(string): exception message + + + [AzureLongRunningJob]: ShouldMethod '{0}' unblocked. + 0(string): methodType + + + +- The parameter : '{0}' is changing. + + + +- The parameter : '{0}' is becoming mandatory. + + + +- The parameter : '{0}' is being replaced by parameter : '{1}'. + + + +- The parameter : '{0}' is being replaced by mandatory parameter : '{1}'. + + + +- Change description : {0} + + + The cmdlet is being deprecated. There will be no replacement for it. + + + The cmdlet parameter set is being deprecated. There will be no replacement for it. + + + The cmdlet '{0}' is replacing this cmdlet. + + + +- The output type is changing from the existing type :'{0}' to the new type :'{1}' + + + +- The output type '{0}' is changing + + + +- The following properties are being added to the output type : + + + +- The following properties in the output type are being deprecated : + + + {0} + + + +- Cmdlet : '{0}' + - {1} + + + Upcoming breaking changes in the cmdlet '{0}' : + + + +- This change will take effect on '{0}' + + + +- The change is expected to take effect from version : '{0}' + + + ```powershell +# Old +{0} + +# New +{1} +``` + + + + +Cmdlet invocation changes : + Old Way : {0} + New Way : {1} + + + +The output type '{0}' is being deprecated without a replacement. + + + +The type of the parameter is changing from '{0}' to '{1}'. + + + +Note : Go to {0} for steps to suppress this breaking change warning, and other information on breaking changes in Azure PowerShell. + + + This cmdlet is in preview. Its behavior is subject to change based on customer feedback. + + + The estimated generally available date is '{0}'. + + + - The change is expected to take effect from Az version : '{0}' + + \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/Response.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Response.cs new file mode 100644 index 000000000000..22dcfa394cb5 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Serialization/JsonSerializer.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Serialization/JsonSerializer.cs new file mode 100644 index 000000000000..d39e351123d1 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Serialization/PropertyTransformation.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Serialization/PropertyTransformation.cs new file mode 100644 index 000000000000..4c81f1a742a4 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/Serialization/SerializationOptions.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Serialization/SerializationOptions.cs new file mode 100644 index 000000000000..44545fae6370 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/SerializationMode.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/SerializationMode.cs new file mode 100644 index 000000000000..c0bc91564679 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/SerializationMode.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.DataBoundary.Runtime +{ + [System.Flags] + public enum SerializationMode + { + None = 0, + IncludeHeaders = 1 << 0, + IncludeRead = 1 << 1, + IncludeCreate = 1 << 2, + IncludeUpdate = 1 << 3, + IncludeAll = IncludeHeaders | IncludeRead | IncludeCreate | IncludeUpdate, + IncludeCreateOrUpdate = IncludeCreate | IncludeUpdate + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/TypeConverterExtensions.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/TypeConverterExtensions.cs new file mode 100644 index 000000000000..ea9e076dd753 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/TypeConverterExtensions.cs @@ -0,0 +1,261 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.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.List SelectToList(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) }.ToList(); + } +#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].ToList(); // 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; + } + 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; + } + + internal static bool Contains(this System.Management.Automation.PSObject psObject, string propertyName) + { + bool result = false; + try + { + var property = System.Linq.Enumerable.FirstOrDefault(psObject.Properties, each => System.String.Equals(each.Name.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + result = property == null ? false : true; + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return result; + } + } +} diff --git a/src/Resources/DataBoundary.Autorest/generated/runtime/UndeclaredResponseException.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/UndeclaredResponseException.cs new file mode 100644 index 000000000000..da50f98f13ca --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/generated/runtime/UndeclaredResponseException.cs @@ -0,0 +1,112 @@ +/*--------------------------------------------------------------------------------------------- + * 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.DataBoundary.Runtime +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using static Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.Json.JsonObject; + + // error message could be in properties.statusMessage + { message = If(json?.Property("properties"), out var p) + && If(p?.PropertyT("statusMessage"), out var sm) + ? (string)sm : (string)Message; } + + // 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. + // In this case, we will assume the response is the expected error message + if(!string.IsNullOrEmpty(ResponseBody)) { + message = ResponseBody; + } + } +#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/Resources/DataBoundary.Autorest/generated/runtime/Writers/JsonWriter.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/Writers/JsonWriter.cs new file mode 100644 index 000000000000..7006bfeca7c9 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/generated/runtime/delegates.cs b/src/Resources/DataBoundary.Autorest/generated/runtime/delegates.cs new file mode 100644 index 000000000000..af67f796000f --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.DataBoundary.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/Resources/DataBoundary.Autorest/help/Az.DataBoundary.md b/src/Resources/DataBoundary.Autorest/help/Az.DataBoundary.md new file mode 100644 index 000000000000..716ecafdbaf2 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/help/Az.DataBoundary.md @@ -0,0 +1,22 @@ +--- +Module Name: Az.DataBoundary +Module Guid: c0d70364-96af-43cf-a3ca-76edff8b31b7 +Download Help Link: https://learn.microsoft.com/powershell/module/az.databoundary +Help Version: 1.0.0.0 +Locale: en-US +--- + +# Az.DataBoundary Module +## Description +Microsoft Azure PowerShell: DataBoundary cmdlets + +## Az.DataBoundary Cmdlets +### [Get-AzDataBoundaryScope](Get-AzDataBoundaryScope.md) +Get data boundary at specified scope + +### [Get-AzDataBoundaryTenant](Get-AzDataBoundaryTenant.md) +Get data boundary of tenant. + +### [Set-AzDataBoundary](Set-AzDataBoundary.md) +Opt-in tenant to data boundary. + diff --git a/src/Resources/DataBoundary.Autorest/help/Get-AzDataBoundaryScope.md b/src/Resources/DataBoundary.Autorest/help/Get-AzDataBoundaryScope.md new file mode 100644 index 000000000000..1fd757953f50 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/help/Get-AzDataBoundaryScope.md @@ -0,0 +1,97 @@ +--- +external help file: +Module Name: Az.Resources +online version: https://learn.microsoft.com/powershell/module/az.resources/get-azdataboundaryscope +schema: 2.0.0 +--- + +# Get-AzDataBoundaryScope + +## SYNOPSIS +Get data boundary at specified scope + +## SYNTAX + +``` +Get-AzDataBoundaryScope -Scope [-DefaultProfile ] [] +``` + +## DESCRIPTION +Get data boundary at specified scope + +## EXAMPLES + +### Example 1: Get Subscription Scoped Data Boundary +```powershell +$scope = "/subscriptions/11111111-1111-1111-1111-111111111111" +Get-AzDataBoundaryScope -Scope $scope +``` + +```output +Name Id Properties +-------- ---- ------------ +00000000-0000-0000-0000-000000000000 /providers/Microsoft.Resources/dataBoundaries/00000000-0000-0000-0000-000000000000 dataBoundary: EU, provisioningState: Created +``` + +Gets the dataBoundary at the subscription scope. + +### Example 2: Get Resource Group Scoped Data Boundary +```powershell +$scope = "/subscriptions/11111111-1111-1111-1111-111111111111/resourcegroups/my-resource-group" +Get-AzDataBoundaryScope -Scope $scope +``` + +```output +Name Id Properties +-------- ---- ------------ +00000000-0000-0000-0000-000000000000 /providers/Microsoft.Resources/dataBoundaries/00000000-0000-0000-0000-000000000000 dataBoundary: EU, provisioningState: Created +``` + +Gets the dataBoundary at the resource group scope. + +## PARAMETERS + +### -DefaultProfile +The DefaultProfile parameter is not functional. +Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + +```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 +``` + +### -Scope +The scope at which the operation is performed. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +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.DataBoundary.Models.IDataBoundaryDefinition + +## NOTES + +## RELATED LINKS + diff --git a/src/Resources/DataBoundary.Autorest/help/Get-AzDataBoundaryTenant.md b/src/Resources/DataBoundary.Autorest/help/Get-AzDataBoundaryTenant.md new file mode 100644 index 000000000000..9fc9c11ae6da --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/help/Get-AzDataBoundaryTenant.md @@ -0,0 +1,67 @@ +--- +external help file: +Module Name: Az.Resources +online version: https://learn.microsoft.com/powershell/module/az.resources/get-azdataboundarytenant +schema: 2.0.0 +--- + +# Get-AzDataBoundaryTenant + +## SYNOPSIS +Get data boundary of tenant. + +## SYNTAX + +``` +Get-AzDataBoundaryTenant [-DefaultProfile ] [] +``` + +## DESCRIPTION +Get data boundary of tenant. + +## EXAMPLES + +### Example 1: Get Tenant Level Data Boundary +```powershell +Get-AzDataBoundaryTenant +``` + +```output +Name Id Properties +-------- ---- ------------ +00000000-0000-0000-0000-000000000000 /providers/Microsoft.Resources/dataBoundaries/00000000-0000-0000-0000-000000000000 dataBoundary: EU, provisioningState: Created +``` + +Gets the dataBoundary at the tenant level. + +## PARAMETERS + +### -DefaultProfile +The DefaultProfile parameter is not functional. +Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + +```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 +``` + +### 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.DataBoundary.Models.IDataBoundaryDefinition + +## NOTES + +## RELATED LINKS + diff --git a/src/Resources/DataBoundary.Autorest/help/README.md b/src/Resources/DataBoundary.Autorest/help/README.md new file mode 100644 index 000000000000..9a0e4bc81b2d --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/help/README.md @@ -0,0 +1,11 @@ +# Docs +This directory contains the documentation of the cmdlets for the `Az.DataBoundary` module. To run documentation generation, use the `generate-help.ps1` script at the root module folder. Files in this folder will *always be overridden on regeneration*. To update documentation examples, please use the `..\examples` folder. + +## Info +- Modifiable: no +- Generated: all +- Committed: yes +- Packaged: yes + +## Details +The process of documentation generation loads `Az.DataBoundary` and analyzes the exported cmdlets from the module. It recognizes the [help comments](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_comment_based_help) that are generated into the scripts in the `..\exports` folder. Additionally, when writing custom cmdlets in the `..\custom` folder, you can use the help comments syntax, which decorate the exported scripts at build-time. The documentation examples are taken from the `..\examples` folder. \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/help/Set-AzDataBoundary.md b/src/Resources/DataBoundary.Autorest/help/Set-AzDataBoundary.md new file mode 100644 index 000000000000..be309330adbf --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/help/Set-AzDataBoundary.md @@ -0,0 +1,180 @@ +--- +external help file: +Module Name: Az.Resources +online version: https://learn.microsoft.com/powershell/module/az.resources/set-azdataboundary +schema: 2.0.0 +--- + +# Set-AzDataBoundary + +## SYNOPSIS +Opt-in tenant to data boundary. + +## SYNTAX + +### PutExpanded (Default) +``` +Set-AzDataBoundary [-DataBoundary ] [-DefaultProfile ] [-Confirm] [-WhatIf] + [] +``` + +### Put +``` +Set-AzDataBoundary -DataBoundaryDefinition [-DefaultProfile ] [-Confirm] + [-WhatIf] [] +``` + +### PutViaJsonFilePath +``` +Set-AzDataBoundary -JsonFilePath [-DefaultProfile ] [-Confirm] [-WhatIf] + [] +``` + +### PutViaJsonString +``` +Set-AzDataBoundary -JsonString [-DefaultProfile ] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Opt-in tenant to data boundary. + +## EXAMPLES + +### Example 1: Set Tenant Level Data Boundary +```powershell +$dataBoundary = "EU" +Set-AzDataBoundary -DataBoundary $dataBoundary +``` + +```output +Name Id Properties +-------- ---- ------------ +00000000-0000-0000-0000-000000000000 /providers/Microsoft.Resources/dataBoundaries/00000000-0000-0000-0000-000000000000 dataBoundary: EU, provisioningState: Created +``` + +Sets the dataBoundary at the tenant level. + +## PARAMETERS + +### -DataBoundary +The data boundary definition. + +```yaml +Type: System.String +Parameter Sets: PutExpanded +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DataBoundaryDefinition +A data boundary definition. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition +Parameter Sets: Put +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -DefaultProfile +The DefaultProfile parameter is not functional. +Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + +```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 +``` + +### -JsonFilePath +Path of Json file supplied to the Put operation + +```yaml +Type: System.String +Parameter Sets: PutViaJsonFilePath +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -JsonString +Json string supplied to the Put operation + +```yaml +Type: System.String +Parameter Sets: PutViaJsonString +Aliases: + +Required: True +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.DataBoundary.Models.IDataBoundaryDefinition + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + +## NOTES + +## RELATED LINKS + diff --git a/src/Resources/DataBoundary.Autorest/how-to.md b/src/Resources/DataBoundary.Autorest/how-to.md new file mode 100644 index 000000000000..2a53249b4a9a --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/how-to.md @@ -0,0 +1,58 @@ +# How-To +This document describes how to develop for `Az.DataBoundary`. + +## Building `Az.DataBoundary` +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.DataBoundary` +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.DataBoundary` +To pack `Az.DataBoundary` 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://learn.microsoft.com/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.DataBoundary`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.DataBoundary.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.DataBoundary.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.DataBoundary`. + - `-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.DataBoundary` 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/Resources/DataBoundary.Autorest/internal/Az.DataBoundary.internal.psm1 b/src/Resources/DataBoundary.Autorest/internal/Az.DataBoundary.internal.psm1 new file mode 100644 index 000000000000..ce9a83fd7d0b --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/internal/Az.DataBoundary.internal.psm1 @@ -0,0 +1,38 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.DataBoundary.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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/Resources/DataBoundary.Autorest/internal/Get-AzDataBoundaryOperation.ps1 b/src/Resources/DataBoundary.Autorest/internal/Get-AzDataBoundaryOperation.ps1 new file mode 100644 index 000000000000..2e2018e91b71 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/internal/Get-AzDataBoundaryOperation.ps1 @@ -0,0 +1,125 @@ + +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Lists all of the available Microsoft.Resources REST API operations. +.Description +Lists all of the available Microsoft.Resources REST API operations. +.Example +{{ Add code here }} +.Example +{{ Add code here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperation +.Link +https://learn.microsoft.com/powershell/module/az.resources/get-azdataboundaryoperation +#> +function Get-AzDataBoundaryOperation { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperation])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Azure')] + [System.Management.Automation.PSObject] + # The DefaultProfile parameter is not functional. + # Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.private\Get-AzDataBoundaryOperation_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/Resources/DataBoundary.Autorest/internal/ProxyCmdletDefinitions.ps1 b/src/Resources/DataBoundary.Autorest/internal/ProxyCmdletDefinitions.ps1 new file mode 100644 index 000000000000..2e2018e91b71 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/internal/ProxyCmdletDefinitions.ps1 @@ -0,0 +1,125 @@ + +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Lists all of the available Microsoft.Resources REST API operations. +.Description +Lists all of the available Microsoft.Resources REST API operations. +.Example +{{ Add code here }} +.Example +{{ Add code here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperation +.Link +https://learn.microsoft.com/powershell/module/az.resources/get-azdataboundaryoperation +#> +function Get-AzDataBoundaryOperation { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IOperation])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Azure')] + [System.Management.Automation.PSObject] + # The DefaultProfile parameter is not functional. + # Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.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.DataBoundary.private\Get-AzDataBoundaryOperation_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/Resources/DataBoundary.Autorest/internal/README.md b/src/Resources/DataBoundary.Autorest/internal/README.md new file mode 100644 index 000000000000..c98a05f65bf5 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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.powershell/blob/main/docs/directives.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.DataBoundary.internal.psm1` file is generated to this folder. This module file handles the hidden cmdlets. These cmdlets will not be exported by `Az.DataBoundary`. Instead, this sub-module is imported by the `..\custom\Az.DataBoundary.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://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_command_precedence?view=powershell-6#qualified-names). For example, `Az.DataBoundary.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.DataBoundary`. diff --git a/src/Resources/DataBoundary.Autorest/pack-module.ps1 b/src/Resources/DataBoundary.Autorest/pack-module.ps1 new file mode 100644 index 000000000000..2f30ca3fffa0 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/pack-module.ps1 @@ -0,0 +1,17 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +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/Resources/DataBoundary.Autorest/run-module.ps1 b/src/Resources/DataBoundary.Autorest/run-module.ps1 new file mode 100644 index 000000000000..d159ff4feb5c --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/run-module.ps1 @@ -0,0 +1,62 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Code) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$isAzure = $true +if($isAzure) { + . (Join-Path $PSScriptRoot 'check-dependencies.ps1') -NotIsolated -Accounts + # Load the latest version of Az.Accounts installed + Import-Module -Name Az.Accounts -RequiredVersion (Get-Module -Name Az.Accounts -ListAvailable | Sort-Object -Property Version -Descending)[0].Version +} + +$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.DataBoundary.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/Resources/DataBoundary.Autorest/test-module.ps1 b/src/Resources/DataBoundary.Autorest/test-module.ps1 new file mode 100644 index 000000000000..200297745276 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/test-module.ps1 @@ -0,0 +1,98 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Live, [switch]$Record, [switch]$Playback, [switch]$RegenerateSupportModule, [switch]$UsePreviousConfigForRecord, [string[]]$TestName) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) +{ + Write-Host -ForegroundColor Green 'Creating isolated process...' + if ($PSBoundParameters.ContainsKey("TestName")) { + $PSBoundParameters["TestName"] = $PSBoundParameters["TestName"] -join "," + } + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +# This is a workaround, since for string array parameter, pwsh -File will only take the first element +if ($PSBoundParameters.ContainsKey("TestName") -and ($TestName.count -eq 1) -and ($TestName[0].Contains(','))) { + $TestName = $TestName[0].Split(",") +} + +$ProgressPreference = 'SilentlyContinue' +$baseName = $PSScriptRoot.BaseName +$requireResourceModule = (($baseName -ne "Resources") -and ($Record.IsPresent -or $Live.IsPresent)) +. (Join-Path $PSScriptRoot 'check-dependencies.ps1') -NotIsolated -Accounts:$false -Pester -Resources:$requireResourceModule -RegenerateSupportModule:$RegenerateSupportModule +. ("$PSScriptRoot\test\utils.ps1") + +if ($requireResourceModule) +{ + # Load the latest Az.Accounts installed + Import-Module -Name Az.Accounts -RequiredVersion (Get-Module -Name Az.Accounts -ListAvailable | Sort-Object -Property Version -Descending)[0].Version + $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.DataBoundary.psd1') +$modulePath = $modulePsd1.FullName +$moduleName = $modulePsd1.BaseName + +Import-Module -Name Pester +Import-Module -Name $modulePath + +$TestMode = 'playback' +$ExcludeTag = @("LiveOnly") +if($Live) +{ + $TestMode = 'live' + $ExcludeTag = @() +} +if($Record) +{ + $TestMode = 'record' +} +try +{ + if ($TestMode -ne 'playback') + { + setupEnv + } else { + $env:AzPSAutorestTestPlaybackMode = $true + } + $testFolder = Join-Path $PSScriptRoot 'test' + if ($null -ne $TestName) + { + Invoke-Pester -Script @{ Path = $testFolder } -TestName $TestName -ExcludeTag $ExcludeTag -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") + } else { + Invoke-Pester -Script @{ Path = $testFolder } -ExcludeTag $ExcludeTag -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") + } +} Finally +{ + if ($TestMode -ne 'playback') + { + cleanupEnv + } + else { + $env:AzPSAutorestTestPlaybackMode = '' + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' diff --git a/src/Resources/DataBoundary.Autorest/test/Get-AzDataBoundaryScope.Recording.json b/src/Resources/DataBoundary.Autorest/test/Get-AzDataBoundaryScope.Recording.json new file mode 100644 index 000000000000..23ad2e26ab51 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/test/Get-AzDataBoundaryScope.Recording.json @@ -0,0 +1,45 @@ +{ + "Get-AzDataBoundaryScope+[NoContext]+Get+$GET+https://management.azure.com//subscriptions/2145a411-d149-4010-84d4-40fe8a55db44/providers/Microsoft.Resources/dataBoundaries/default?api-version=2024-08-01+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com//subscriptions/2145a411-d149-4010-84d4-40fe8a55db44/providers/Microsoft.Resources/dataBoundaries/default?api-version=2024-08-01", + "Content": null, + "isContentBase64": false, + "Headers": { + "x-ms-unique-id": [ "1" ], + "x-ms-client-request-id": [ "f4553e47-d848-4c63-9d25-89d975070e6e" ], + "CommandName": [ "Get-AzDataBoundaryScope" ], + "FullCommandName": [ "Get-AzDataBoundaryScope_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/v9.5.0", "PSVersion/v7.4.5", "Az.DataBoundary/0.1.1" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "1099" ], + "x-ms-ratelimit-remaining-subscription-global-reads": [ "16499" ], + "x-ms-request-id": [ "eb899057-8bdd-482d-9146-a15a823e3f02" ], + "x-ms-correlation-request-id": [ "eb899057-8bdd-482d-9146-a15a823e3f02" ], + "x-ms-routing-request-id": [ "WESTUS:20241029T163850Z:eb899057-8bdd-482d-9146-a15a823e3f02" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "X-Cache": [ "CONFIG_NOCACHE" ], + "X-MSEdge-Ref": [ "Ref A: 3D3C693463E64E7091E8EFC801F2986F Ref B: SJC211051205053 Ref C: 2024-10-29T16:38:50Z" ], + "Date": [ "Tue, 29 Oct 2024 16:38:50 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "208" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/providers/Microsoft.Resources/dataBoundaries/72f988bf-86f1-41af-91ab-2d7cd011db47\",\"name\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\",\"properties\":{\"dataBoundary\":\"Global\",\"provisioningState\":\"Succeeded\"}}", + "isContentBase64": false + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/test/Get-AzDataBoundaryScope.Tests.ps1 b/src/Resources/DataBoundary.Autorest/test/Get-AzDataBoundaryScope.Tests.ps1 new file mode 100644 index 000000000000..66495c79e35d --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/test/Get-AzDataBoundaryScope.Tests.ps1 @@ -0,0 +1,27 @@ +if(($null -eq $TestName) -or ($TestName -contains 'Get-AzDataBoundaryScope')) +{ + $loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' + if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' + } + . ($loadEnvPath) + $TestRecordingFile = Join-Path $PSScriptRoot 'Get-AzDataBoundaryScope.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-AzDataBoundaryScope' { + It 'Get' { + { + $scope = "/subscriptions/" + $env.SubscriptionId + $default = "default" + $boundaryData = Get-AzDataBoundaryScope -Scope $scope -DefaultProfile $default + $boundaryData.DataBoundary | Should -Be "Global" + $boundaryData.ProvisioningState | Should -Be "Succeeded" + } | Should -Not -Throw + } +} diff --git a/src/Resources/DataBoundary.Autorest/test/Get-AzDataBoundaryTenant.Recording.json b/src/Resources/DataBoundary.Autorest/test/Get-AzDataBoundaryTenant.Recording.json new file mode 100644 index 000000000000..e604c9d06b47 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/test/Get-AzDataBoundaryTenant.Recording.json @@ -0,0 +1,44 @@ +{ + "Get-AzDataBoundaryTenant+[NoContext]+Get+$GET+https://management.azure.com/providers/Microsoft.Resources/dataBoundaries/default?api-version=2024-08-01+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/providers/Microsoft.Resources/dataBoundaries/default?api-version=2024-08-01", + "Content": null, + "isContentBase64": false, + "Headers": { + "x-ms-unique-id": [ "2" ], + "x-ms-client-request-id": [ "084f5792-a867-43a4-a5e8-4826c7a85de8" ], + "CommandName": [ "Get-AzDataBoundaryTenant" ], + "FullCommandName": [ "Get-AzDataBoundaryTenant_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/v9.5.0", "PSVersion/v7.4.5", "Az.DataBoundary/0.1.1" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-tenant-reads": [ "2199" ], + "x-ms-request-id": [ "7b7ec950-c8d8-4d7e-8607-0eeec786ad16" ], + "x-ms-correlation-request-id": [ "7b7ec950-c8d8-4d7e-8607-0eeec786ad16" ], + "x-ms-routing-request-id": [ "WESTUS:20241029T163851Z:7b7ec950-c8d8-4d7e-8607-0eeec786ad16" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "X-Cache": [ "CONFIG_NOCACHE" ], + "X-MSEdge-Ref": [ "Ref A: BB33C476B19643739A92372CDFF6D136 Ref B: SJC211051205053 Ref C: 2024-10-29T16:38:51Z" ], + "Date": [ "Tue, 29 Oct 2024 16:38:50 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "208" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/providers/Microsoft.Resources/dataBoundaries/72f988bf-86f1-41af-91ab-2d7cd011db47\",\"name\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\",\"properties\":{\"dataBoundary\":\"Global\",\"provisioningState\":\"Succeeded\"}}", + "isContentBase64": false + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/test/Get-AzDataBoundaryTenant.Tests.ps1 b/src/Resources/DataBoundary.Autorest/test/Get-AzDataBoundaryTenant.Tests.ps1 new file mode 100644 index 000000000000..05f92eb6b497 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/test/Get-AzDataBoundaryTenant.Tests.ps1 @@ -0,0 +1,26 @@ +if(($null -eq $TestName) -or ($TestName -contains 'Get-AzDataBoundaryTenant')) +{ + $loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' + if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' + } + . ($loadEnvPath) + $TestRecordingFile = Join-Path $PSScriptRoot 'Get-AzDataBoundaryTenant.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-AzDataBoundaryTenant' { + It 'Get' { + { + $default = "default" + $boundaryData = Get-AzDataBoundaryTenant -DefaultProfile $default + $boundaryData.DataBoundary | Should -Be "Global" + $boundaryData.ProvisioningState | Should -Be "Succeeded" + } | Should -Not -Throw + } +} diff --git a/src/Resources/DataBoundary.Autorest/test/README.md b/src/Resources/DataBoundary.Autorest/test/README.md new file mode 100644 index 000000000000..7c752b4c8c43 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/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/Resources/DataBoundary.Autorest/test/Set-AzDataBoundary.Recording.json b/src/Resources/DataBoundary.Autorest/test/Set-AzDataBoundary.Recording.json new file mode 100644 index 000000000000..0d3d45da30b4 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/test/Set-AzDataBoundary.Recording.json @@ -0,0 +1,39 @@ +{ + "Set-AzDataBoundary+[NoContext]+Put+$PUT+https://management.azure.com/providers/Microsoft.Resources/dataBoundaries/default?api-version=2024-08-01+1": { + "Request": { + "Method": "PUT", + "RequestUri": "https://management.azure.com/providers/Microsoft.Resources/dataBoundaries/default?api-version=2024-08-01", + "Content": "{\r\n \"properties\": {\r\n \"dataBoundary\": \"EU\"\r\n }\r\n}", + "isContentBase64": false, + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "54" ] + } + }, + "Response": { + "StatusCode": 403, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-failure-cause": [ "gateway" ], + "x-ms-request-id": [ "ee6a71d9-fde6-42b8-a5f7-937662cf9bb7" ], + "x-ms-correlation-request-id": [ "ee6a71d9-fde6-42b8-a5f7-937662cf9bb7" ], + "x-ms-routing-request-id": [ "WESTUS:20241029T163851Z:ee6a71d9-fde6-42b8-a5f7-937662cf9bb7" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "X-Cache": [ "CONFIG_NOCACHE" ], + "X-MSEdge-Ref": [ "Ref A: 47CB5B974B8440FAB184D8889D55C387 Ref B: SJC211051205053 Ref C: 2024-10-29T16:38:51Z" ], + "Date": [ "Tue, 29 Oct 2024 16:38:51 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "391" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"error\":{\"code\":\"AuthorizationFailed\",\"message\":\"The client \u0027skadhiresan@microsoft.com\u0027 with object id \u00279c7d4781-a31a-4fd3-9566-f2af58409dd3\u0027 does not have authorization to perform action \u0027Microsoft.Resources/dataBoundaries/write\u0027 over scope \u0027/providers/Microsoft.Resources/dataBoundaries/default\u0027 or the scope is invalid. If access was recently granted, please refresh your credentials.\"}}", + "isContentBase64": false + } + } +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/test/Set-AzDataBoundary.Tests.ps1 b/src/Resources/DataBoundary.Autorest/test/Set-AzDataBoundary.Tests.ps1 new file mode 100644 index 000000000000..03d900b0d8e0 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/test/Set-AzDataBoundary.Tests.ps1 @@ -0,0 +1,27 @@ +if(($null -eq $TestName) -or ($TestName -contains 'Set-AzDataBoundary')) +{ + $loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' + if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' + } + . ($loadEnvPath) + $TestRecordingFile = Join-Path $PSScriptRoot 'Set-AzDataBoundary.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 'Set-AzDataBoundary' { + It 'Put' { + { + $dataBoundary = "EU" + $default = "default" + $exception = Set-AzDataBoundary -DataBoundary $dataBoundary -DefaultProfile $default + $exception -contains "does not have authorization to perform action" | Should -Be True + $exception -contains "or the scope is invalid. If access was recently granted, please refresh your credentials." | Should -Be True + } | Should -Throw + } +} diff --git a/src/Resources/DataBoundary.Autorest/test/env.json b/src/Resources/DataBoundary.Autorest/test/env.json new file mode 100644 index 000000000000..ce140dcc6a3c --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/test/env.json @@ -0,0 +1,4 @@ +{ + "SubscriptionId": "2145a411-d149-4010-84d4-40fe8a55db44", + "Tenant": "72f988bf-86f1-41af-91ab-2d7cd011db47" +} diff --git a/src/Resources/DataBoundary.Autorest/test/loadEnv.ps1 b/src/Resources/DataBoundary.Autorest/test/loadEnv.ps1 new file mode 100644 index 000000000000..6a7c385c6b7d --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/test/loadEnv.ps1 @@ -0,0 +1,29 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +$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=@{"*:Tenant"=$env.Tenant} +} \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/test/localEnv.json b/src/Resources/DataBoundary.Autorest/test/localEnv.json new file mode 100644 index 000000000000..1c1c14c7f8ea --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/test/localEnv.json @@ -0,0 +1,4 @@ +{ + "Tenant": "8e3c5456-cb2d-4f52-bef9-4581cf5eb1cb", + "SubscriptionId": "1200d73d-d350-413a-98c5-e77ca51245de" +} diff --git a/src/Resources/DataBoundary.Autorest/test/utils.ps1 b/src/Resources/DataBoundary.Autorest/test/utils.ps1 new file mode 100644 index 000000000000..f8497fbd7da0 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/test/utils.ps1 @@ -0,0 +1,56 @@ +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]$_}) + } +} +function Start-TestSleep { + [CmdletBinding(DefaultParameterSetName = 'SleepBySeconds')] + param( + [parameter(Mandatory = $true, Position = 0, ParameterSetName = 'SleepBySeconds')] + [ValidateRange(0.0, 2147483.0)] + [double] $Seconds, + + [parameter(Mandatory = $true, ParameterSetName = 'SleepByMilliseconds')] + [ValidateRange('NonNegative')] + [Alias('ms')] + [int] $Milliseconds + ) + + if ($TestMode -ne 'playback') { + switch ($PSCmdlet.ParameterSetName) { + 'SleepBySeconds' { + Start-Sleep -Seconds $Seconds + } + 'SleepByMilliseconds' { + Start-Sleep -Milliseconds $Milliseconds + } + } + } +} + +$env = @{} +if ($UsePreviousConfigForRecord) { + $previousEnv = Get-Content (Join-Path $PSScriptRoot 'env.json') | ConvertFrom-Json + $previousEnv.psobject.properties | Foreach-Object { $env[$_.Name] = $_.Value } +} +# Add script method called AddWithCache to $env, when useCache is set true, it will try to get the value from the $env first. +# example: $val = $env.AddWithCache('key', $val, $true) +$env | Add-Member -Type ScriptMethod -Value { param( [string]$key, [object]$val, [bool]$useCache) if ($this.Contains($key) -and $useCache) { return $this[$key] } else { $this[$key] = $val; return $val } } -Name 'AddWithCache' +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/src/Resources/DataBoundary.Autorest/utils/Get-SubscriptionIdTestSafe.ps1 b/src/Resources/DataBoundary.Autorest/utils/Get-SubscriptionIdTestSafe.ps1 new file mode 100644 index 000000000000..5319862d3372 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/utils/Get-SubscriptionIdTestSafe.ps1 @@ -0,0 +1,7 @@ +param() +if ($env:AzPSAutorestTestPlaybackMode) { + $loadEnvPath = Join-Path $PSScriptRoot '..' 'test' 'loadEnv.ps1' + . ($loadEnvPath) + return $env.SubscriptionId +} +return (Get-AzContext).Subscription.Id \ No newline at end of file diff --git a/src/Resources/DataBoundary.Autorest/utils/Unprotect-SecureString.ps1 b/src/Resources/DataBoundary.Autorest/utils/Unprotect-SecureString.ps1 new file mode 100644 index 000000000000..cb05b51a6220 --- /dev/null +++ b/src/Resources/DataBoundary.Autorest/utils/Unprotect-SecureString.ps1 @@ -0,0 +1,16 @@ +#This script converts securestring to plaintext + +param( + [Parameter(Mandatory, ValueFromPipeline)] + [System.Security.SecureString] + ${SecureString} +) + +$ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString) +try { + $plaintext = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr) +} finally { + [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr) +} + +return $plaintext \ No newline at end of file diff --git a/src/Resources/Policy.Autorest/test/Backcompat/GetBuiltinsByName.Tests.ps1 b/src/Resources/Policy.Autorest/test/Backcompat/GetBuiltinsByName.Tests.ps1 index 51bf5c00ae45..b25355aea03a 100644 --- a/src/Resources/Policy.Autorest/test/Backcompat/GetBuiltinsByName.Tests.ps1 +++ b/src/Resources/Policy.Autorest/test/Backcompat/GetBuiltinsByName.Tests.ps1 @@ -7,8 +7,7 @@ Describe 'Backcompat-GetBuiltinsByName' -Tag 'LiveOnly' { { # policy definitions $builtins = Get-AzPolicyDefinition -Builtin -BackwardCompatible | Select-Object -First 100 - foreach ($builtin in $builtins) - { + foreach ($builtin in $builtins) { $done = $false do { try { @@ -35,8 +34,7 @@ Describe 'Backcompat-GetBuiltinsByName' -Tag 'LiveOnly' { { # policy set definitions $builtins = Get-AzPolicySetDefinition -Builtin -BackwardCompatible | Select-Object -First 100 - foreach ($builtin in $builtins) - { + foreach ($builtin in $builtins) { $done = $false do { try { diff --git a/src/Resources/Resources.sln b/src/Resources/Resources.sln index 1da100312d49..adba9edb307e 100644 --- a/src/Resources/Resources.sln +++ b/src/Resources/Resources.sln @@ -63,6 +63,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Az.Policy", "Policy.Autores EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Az.Metricdata", "..\Monitor\MetricData.Autorest\Az.Metricdata.csproj", "{C8338D4A-8D88-4805-B7C6-AAF154AB67B9}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Az.DataBoundary", "DataBoundary.Autorest\Az.DataBoundary.csproj", "{4087BDF7-B159-4125-B5F7-9BA71DF6AC70}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -182,6 +184,10 @@ Global {C8338D4A-8D88-4805-B7C6-AAF154AB67B9}.Debug|Any CPU.Build.0 = Debug|Any CPU {C8338D4A-8D88-4805-B7C6-AAF154AB67B9}.Release|Any CPU.ActiveCfg = Release|Any CPU {C8338D4A-8D88-4805-B7C6-AAF154AB67B9}.Release|Any CPU.Build.0 = Release|Any CPU + {4087BDF7-B159-4125-B5F7-9BA71DF6AC70}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4087BDF7-B159-4125-B5F7-9BA71DF6AC70}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4087BDF7-B159-4125-B5F7-9BA71DF6AC70}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4087BDF7-B159-4125-B5F7-9BA71DF6AC70}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {5323D4CC-D4B7-44A7-B79A-F91C47AC9650} = {23F657BD-37C1-4E91-8548-5783E43D40B0} diff --git a/src/Resources/Resources/Az.Resources.psd1 b/src/Resources/Resources/Az.Resources.psd1 index b861b3ad618f..682f66f8158d 100644 --- a/src/Resources/Resources/Az.Resources.psd1 +++ b/src/Resources/Resources/Az.Resources.psd1 @@ -3,7 +3,7 @@ # # Generated by: Microsoft Corporation # -# Generated on: 10/17/2024 +# Generated on: 10/30/2024 # @{ @@ -57,6 +57,7 @@ RequiredModules = @(@{ModuleName = 'Az.Accounts'; ModuleVersion = '3.0.4'; }) # Assemblies that must be loaded prior to importing this module RequiredAssemblies = 'Authorization.Autorest/bin/Az.Authorization.private.dll', + 'DataBoundary.Autorest/bin/Az.DataBoundary.private.dll', 'Microsoft.Azure.Management.ManagementGroups.dll', 'Microsoft.Azure.Management.ResourceManager.dll', 'Microsoft.Azure.PowerShell.Authorization.Management.Sdk.dll', @@ -78,6 +79,7 @@ TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module FormatsToProcess = 'Authorization.Autorest/Az.Authorization.format.ps1xml', + 'DataBoundary.Autorest/Az.DataBoundary.format.ps1xml', 'MSGraph.Autorest/Az.MSGraph.format.ps1xml', 'Policy.Autorest/Az.Policy.format.ps1xml', 'ResourceManager.format.ps1xml', @@ -86,6 +88,7 @@ FormatsToProcess = 'Authorization.Autorest/Az.Authorization.format.ps1xml', # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess NestedModules = @('Authorization.Autorest/Az.Authorization.psm1', + 'DataBoundary.Autorest/Az.DataBoundary.psm1', 'Microsoft.Azure.PowerShell.Cmdlets.ResourceManager.dll', 'Microsoft.Azure.PowerShell.Cmdlets.Resources.dll', 'Microsoft.Azure.PowerShell.Cmdlets.Tags.dll', @@ -99,7 +102,8 @@ FunctionsToExport = 'Add-AzADAppPermission', 'Add-AzADGroupMember', 'Get-AzADGroupMember', 'Get-AzADGroupOwner', 'Get-AzADOrganization', 'Get-AzADServicePrincipal', 'Get-AzADServicePrincipalAppRoleAssignment', 'Get-AzADSpCredential', - 'Get-AzADUser', 'Get-AzPolicyAssignment', 'Get-AzPolicyDefinition', + 'Get-AzADUser', 'Get-AzDataBoundaryScope', 'Get-AzDataBoundaryTenant', + 'Get-AzPolicyAssignment', 'Get-AzPolicyDefinition', 'Get-AzPolicyExemption', 'Get-AzPolicySetDefinition', 'Get-AzRoleAssignmentSchedule', 'Get-AzRoleAssignmentScheduleInstance', @@ -126,7 +130,7 @@ FunctionsToExport = 'Add-AzADAppPermission', 'Add-AzADGroupMember', 'Remove-AzPolicyAssignment', 'Remove-AzPolicyDefinition', 'Remove-AzPolicyExemption', 'Remove-AzPolicySetDefinition', 'Remove-AzRoleManagementPolicy', - 'Remove-AzRoleManagementPolicyAssignment', + 'Remove-AzRoleManagementPolicyAssignment', 'Set-AzDataBoundary', 'Stop-AzRoleAssignmentScheduleRequest', 'Stop-AzRoleEligibilityScheduleRequest', 'Update-AzADAppFederatedCredential', 'Update-AzADApplication', diff --git a/src/Resources/Resources/ChangeLog.md b/src/Resources/Resources/ChangeLog.md index 8d9105673ca7..b686faf459e8 100644 --- a/src/Resources/Resources/ChangeLog.md +++ b/src/Resources/Resources/ChangeLog.md @@ -20,6 +20,7 @@ ## Upcoming Release * Fixed customer-reported `Remove-AzPolicyAssignment` behavior. +* Added new cmdlets of DataBoundary ## Version 7.5.0 * Added `ResourceSelector` and `Override` parameters to `New/Update-AzPolicyAssignment`. diff --git a/src/Resources/Resources/help/Az.Resources.md b/src/Resources/Resources/help/Az.Resources.md index cb1bd29a4b19..521b9dd2d692 100644 --- a/src/Resources/Resources/help/Az.Resources.md +++ b/src/Resources/Resources/help/Az.Resources.md @@ -65,6 +65,12 @@ Lists key credentials and password credentials for an service principal. ### [Get-AzADUser](Get-AzADUser.md) Lists entities from users or get entity from users by key +### [Get-AzDataBoundaryScope](Get-AzDataBoundaryScope.md) +Get data boundary at specified scope + +### [Get-AzDataBoundaryTenant](Get-AzDataBoundaryTenant.md) +Get data boundary of tenant. + ### [Get-AzDenyAssignment](Get-AzDenyAssignment.md) Lists Azure RBAC deny assignments at the specified scope. By default it lists all deny assignments in the selected Azure subscription. @@ -549,6 +555,9 @@ Saves a Subscription scoped Deployment Stack Template. ### [Save-AzTenantDeploymentTemplate](Save-AzTenantDeploymentTemplate.md) Saves a deployment template to a file. +### [Set-AzDataBoundary](Set-AzDataBoundary.md) +Opt-in tenant to data boundary. + ### [Set-AzManagedApplication](Set-AzManagedApplication.md) Updates managed application @@ -648,19 +657,19 @@ Removes a feature registration from your account. Unregisters a resource provider. ### [Update-AzADAppFederatedCredential](Update-AzADAppFederatedCredential.md) -Update the navigation property federatedIdentityCredentials in applications +update the navigation property federatedIdentityCredentials in applications ### [Update-AzADApplication](Update-AzADApplication.md) Updates entity in applications ### [Update-AzADGroup](Update-AzADGroup.md) -Update entity in groups +update entity in groups ### [Update-AzADServicePrincipal](Update-AzADServicePrincipal.md) Updates entity in service principal ### [Update-AzADServicePrincipalAppRoleAssignment](Update-AzADServicePrincipalAppRoleAssignment.md) -Update the navigation property appRoleAssignments in servicePrincipals +update the navigation property appRoleAssignments in servicePrincipals ### [Update-AzADUser](Update-AzADUser.md) Updates entity in users diff --git a/src/Resources/Resources/help/Get-AzDataBoundaryScope.md b/src/Resources/Resources/help/Get-AzDataBoundaryScope.md new file mode 100644 index 000000000000..efb72d995744 --- /dev/null +++ b/src/Resources/Resources/help/Get-AzDataBoundaryScope.md @@ -0,0 +1,112 @@ +--- +external help file: Az.Resources-help.xml +Module Name: Az.Resources +online version: https://learn.microsoft.com/powershell/module/az.resources/get-azdataboundaryscope +schema: 2.0.0 +--- + +# Get-AzDataBoundaryScope + +## SYNOPSIS +Get data boundary at specified scope + +## SYNTAX + +``` +Get-AzDataBoundaryScope -Scope [-DefaultProfile ] [-ProgressAction ] + [] +``` + +## DESCRIPTION +Get data boundary at specified scope + +## EXAMPLES + +### Example 1: Get Subscription Scoped Data Boundary +```powershell +$scope = "/subscriptions/11111111-1111-1111-1111-111111111111" +Get-AzDataBoundaryScope -Scope $scope +``` + +```output +Name Id Properties +-------- ---- ------------ +00000000-0000-0000-0000-000000000000 /providers/Microsoft.Resources/dataBoundaries/00000000-0000-0000-0000-000000000000 dataBoundary: EU, provisioningState: Created +``` + +Gets the dataBoundary at the subscription scope. + +### Example 2: Get Resource Group Scoped Data Boundary +```powershell +$scope = "/subscriptions/11111111-1111-1111-1111-111111111111/resourcegroups/my-resource-group" +Get-AzDataBoundaryScope -Scope $scope +``` + +```output +Name Id Properties +-------- ---- ------------ +00000000-0000-0000-0000-000000000000 /providers/Microsoft.Resources/dataBoundaries/00000000-0000-0000-0000-000000000000 dataBoundary: EU, provisioningState: Created +``` + +Gets the dataBoundary at the resource group scope. + +## PARAMETERS + +### -DefaultProfile +The DefaultProfile parameter is not functional. +Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + +```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 +``` + +### -ProgressAction +{{ Fill ProgressAction Description }} + +```yaml +Type: System.Management.Automation.ActionPreference +Parameter Sets: (All) +Aliases: proga + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Scope +The scope at which the operation is performed. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +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.DataBoundary.Models.IDataBoundaryDefinition + +## NOTES + +## RELATED LINKS diff --git a/src/Resources/Resources/help/Get-AzDataBoundaryTenant.md b/src/Resources/Resources/help/Get-AzDataBoundaryTenant.md new file mode 100644 index 000000000000..97b5ad68b454 --- /dev/null +++ b/src/Resources/Resources/help/Get-AzDataBoundaryTenant.md @@ -0,0 +1,81 @@ +--- +external help file: Az.Resources-help.xml +Module Name: Az.Resources +online version: https://learn.microsoft.com/powershell/module/az.resources/get-azdataboundarytenant +schema: 2.0.0 +--- + +# Get-AzDataBoundaryTenant + +## SYNOPSIS +Get data boundary of tenant. + +## SYNTAX + +``` +Get-AzDataBoundaryTenant [-DefaultProfile ] [-ProgressAction ] [] +``` + +## DESCRIPTION +Get data boundary of tenant. + +## EXAMPLES + +### Example 1: Get Tenant Level Data Boundary +```powershell +Get-AzDataBoundaryTenant +``` + +```output +Name Id Properties +-------- ---- ------------ +00000000-0000-0000-0000-000000000000 /providers/Microsoft.Resources/dataBoundaries/00000000-0000-0000-0000-000000000000 dataBoundary: EU, provisioningState: Created +``` + +Gets the dataBoundary at the tenant level. + +## PARAMETERS + +### -DefaultProfile +The DefaultProfile parameter is not functional. +Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + +```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 +``` + +### -ProgressAction +{{ Fill ProgressAction Description }} + +```yaml +Type: System.Management.Automation.ActionPreference +Parameter Sets: (All) +Aliases: proga + +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.DataBoundary.Models.IDataBoundaryDefinition + +## NOTES + +## RELATED LINKS diff --git a/src/Resources/Resources/help/Set-AzDataBoundary.md b/src/Resources/Resources/help/Set-AzDataBoundary.md new file mode 100644 index 000000000000..bf6c22965e4d --- /dev/null +++ b/src/Resources/Resources/help/Set-AzDataBoundary.md @@ -0,0 +1,195 @@ +--- +external help file: Az.Resources-help.xml +Module Name: Az.Resources +online version: https://learn.microsoft.com/powershell/module/az.resources/set-azdataboundary +schema: 2.0.0 +--- + +# Set-AzDataBoundary + +## SYNOPSIS +Opt-in tenant to data boundary. + +## SYNTAX + +### PutExpanded (Default) +``` +Set-AzDataBoundary [-DataBoundary ] [-DefaultProfile ] [-ProgressAction ] + [-WhatIf] [-Confirm] [] +``` + +### Put +``` +Set-AzDataBoundary -DataBoundaryDefinition [-DefaultProfile ] + [-ProgressAction ] [-WhatIf] [-Confirm] [] +``` + +### PutViaJsonFilePath +``` +Set-AzDataBoundary -JsonFilePath [-DefaultProfile ] [-ProgressAction ] + [-WhatIf] [-Confirm] [] +``` + +### PutViaJsonString +``` +Set-AzDataBoundary -JsonString [-DefaultProfile ] [-ProgressAction ] + [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +Opt-in tenant to data boundary. + +## EXAMPLES + +### Example 1: Set Tenant Level Data Boundary +```powershell +$dataBoundary = "EU" +Set-AzDataBoundary -DataBoundary $dataBoundary +``` + +```output +Name Id Properties +-------- ---- ------------ +00000000-0000-0000-0000-000000000000 /providers/Microsoft.Resources/dataBoundaries/00000000-0000-0000-0000-000000000000 dataBoundary: EU, provisioningState: Created +``` + +Sets the dataBoundary at the tenant level. + +## PARAMETERS + +### -DataBoundary +The data boundary definition. + +```yaml +Type: System.String +Parameter Sets: PutExpanded +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DataBoundaryDefinition +A data boundary definition. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition +Parameter Sets: Put +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -DefaultProfile +The DefaultProfile parameter is not functional. +Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + +```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 +``` + +### -JsonFilePath +Path of Json file supplied to the Put operation + +```yaml +Type: System.String +Parameter Sets: PutViaJsonFilePath +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -JsonString +Json string supplied to the Put operation + +```yaml +Type: System.String +Parameter Sets: PutViaJsonString +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ProgressAction +{{ Fill ProgressAction Description }} + +```yaml +Type: System.Management.Automation.ActionPreference +Parameter Sets: (All) +Aliases: proga + +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.DataBoundary.Models.IDataBoundaryDefinition + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.DataBoundary.Models.IDataBoundaryDefinition + +## NOTES + +## RELATED LINKS diff --git a/tools/StaticAnalysis/Exceptions/Az.Resources/Az.Resources/UXMetadataIssues.csv b/tools/StaticAnalysis/Exceptions/Az.Resources/Az.Resources/UXMetadataIssues.csv new file mode 100644 index 000000000000..7f5bf8c270fb --- /dev/null +++ b/tools/StaticAnalysis/Exceptions/Az.Resources/Az.Resources/UXMetadataIssues.csv @@ -0,0 +1,3 @@ +"Module","Severity","ResourceType","SubResourceType","Command","Description" +"Az.Resources","1","Microsoft.Resources","dataBoundaries","","ArrayItemNotValid: #/commands[1]\n{\n ArrayItemNotValid: #/commands[1].help.parameterSets[0]\n {\n ArrayExpected: #/commands[1].help.parameterSets[0].parameters\n }\n \n ArrayItemNotValid: #/commands[1].examples[0]\n {\n ArrayExpected: #/commands[1].examples[0].parameters\n }\n \n}\n" +"Az.Resources","1","Microsoft.Resources","dataBoundaries","Get-AzDataBoundaryScope","default is defined in path but cannot find in example"